preferences.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Searx preferences implementation.
  3. """
  4. from __future__ import annotations
  5. # pylint: disable=useless-object-inheritance
  6. from base64 import urlsafe_b64encode, urlsafe_b64decode
  7. from zlib import compress, decompress
  8. from urllib.parse import parse_qs, urlencode
  9. from typing import Iterable, Dict, List, Optional
  10. from collections import OrderedDict
  11. import flask
  12. import babel
  13. import searx.plugins
  14. from searx import settings, autocomplete, favicons
  15. from searx.enginelib import Engine
  16. from searx.engines import DEFAULT_CATEGORY
  17. from searx.extended_types import SXNG_Request
  18. from searx.locales import LOCALE_NAMES
  19. from searx.webutils import VALID_LANGUAGE_CODE
  20. COOKIE_MAX_AGE = 60 * 60 * 24 * 365 * 5 # 5 years
  21. DOI_RESOLVERS = list(settings['doi_resolvers'])
  22. MAP_STR2BOOL: Dict[str, bool] = OrderedDict(
  23. [
  24. ('0', False),
  25. ('1', True),
  26. ('on', True),
  27. ('off', False),
  28. ('True', True),
  29. ('False', False),
  30. ('none', False),
  31. ]
  32. )
  33. class ValidationException(Exception):
  34. """Exption from ``cls.__init__`` when configuration value is invalid."""
  35. class Setting:
  36. """Base class of user settings"""
  37. def __init__(self, default_value, locked: bool = False):
  38. super().__init__()
  39. self.value = default_value
  40. self.locked = locked
  41. def parse(self, data: str):
  42. """Parse ``data`` and store the result at ``self.value``
  43. If needed, its overwritten in the inheritance.
  44. """
  45. self.value = data
  46. def get_value(self):
  47. """Returns the value of the setting
  48. If needed, its overwritten in the inheritance.
  49. """
  50. return self.value
  51. def save(self, name: str, resp: flask.Response):
  52. """Save cookie ``name`` in the HTTP response object
  53. If needed, its overwritten in the inheritance."""
  54. resp.set_cookie(name, self.value, max_age=COOKIE_MAX_AGE)
  55. class StringSetting(Setting):
  56. """Setting of plain string values"""
  57. class EnumStringSetting(Setting):
  58. """Setting of a value which can only come from the given choices"""
  59. def __init__(self, default_value: str, choices: Iterable[str], locked=False):
  60. super().__init__(default_value, locked)
  61. self.choices = choices
  62. self._validate_selection(self.value)
  63. def _validate_selection(self, selection: str):
  64. if selection not in self.choices:
  65. raise ValidationException('Invalid value: "{0}"'.format(selection))
  66. def parse(self, data: str):
  67. """Parse and validate ``data`` and store the result at ``self.value``"""
  68. self._validate_selection(data)
  69. self.value = data
  70. class MultipleChoiceSetting(Setting):
  71. """Setting of values which can only come from the given choices"""
  72. def __init__(self, default_value: List[str], choices: Iterable[str], locked=False):
  73. super().__init__(default_value, locked)
  74. self.choices = choices
  75. self._validate_selections(self.value)
  76. def _validate_selections(self, selections: List[str]):
  77. for item in selections:
  78. if item not in self.choices:
  79. raise ValidationException('Invalid value: "{0}"'.format(selections))
  80. def parse(self, data: str):
  81. """Parse and validate ``data`` and store the result at ``self.value``"""
  82. if data == '':
  83. self.value = []
  84. return
  85. elements = data.split(',')
  86. self._validate_selections(elements)
  87. self.value = elements
  88. def parse_form(self, data: List[str]):
  89. if self.locked:
  90. return
  91. self.value = []
  92. for choice in data:
  93. if choice in self.choices and choice not in self.value:
  94. self.value.append(choice)
  95. def save(self, name: str, resp: flask.Response):
  96. """Save cookie ``name`` in the HTTP response object"""
  97. resp.set_cookie(name, ','.join(self.value), max_age=COOKIE_MAX_AGE)
  98. class SetSetting(Setting):
  99. """Setting of values of type ``set`` (comma separated string)"""
  100. def __init__(self, *args, **kwargs):
  101. super().__init__(*args, **kwargs)
  102. self.values = set()
  103. def get_value(self):
  104. """Returns a string with comma separated values."""
  105. return ','.join(self.values)
  106. def parse(self, data: str):
  107. """Parse and validate ``data`` and store the result at ``self.value``"""
  108. if data == '':
  109. self.values = set()
  110. return
  111. elements = data.split(',')
  112. for element in elements:
  113. self.values.add(element)
  114. def parse_form(self, data: str):
  115. if self.locked:
  116. return
  117. elements = data.split(',')
  118. self.values = set(elements)
  119. def save(self, name: str, resp: flask.Response):
  120. """Save cookie ``name`` in the HTTP response object"""
  121. resp.set_cookie(name, ','.join(self.values), max_age=COOKIE_MAX_AGE)
  122. class SearchLanguageSetting(EnumStringSetting):
  123. """Available choices may change, so user's value may not be in choices anymore"""
  124. def _validate_selection(self, selection):
  125. if selection != '' and selection != 'auto' and not VALID_LANGUAGE_CODE.match(selection):
  126. raise ValidationException('Invalid language code: "{0}"'.format(selection))
  127. def parse(self, data: str):
  128. """Parse and validate ``data`` and store the result at ``self.value``"""
  129. if data not in self.choices and data != self.value:
  130. # hack to give some backwards compatibility with old language cookies
  131. data = str(data).replace('_', '-')
  132. lang = data.split('-', maxsplit=1)[0]
  133. if data in self.choices:
  134. pass
  135. elif lang in self.choices:
  136. data = lang
  137. else:
  138. data = self.value
  139. self._validate_selection(data)
  140. self.value = data
  141. class MapSetting(Setting):
  142. """Setting of a value that has to be translated in order to be storable"""
  143. def __init__(self, default_value, map: Dict[str, object], locked=False): # pylint: disable=redefined-builtin
  144. super().__init__(default_value, locked)
  145. self.map = map
  146. if self.value not in self.map.values():
  147. raise ValidationException('Invalid default value')
  148. def parse(self, data: str):
  149. """Parse and validate ``data`` and store the result at ``self.value``"""
  150. if data not in self.map:
  151. raise ValidationException('Invalid choice: {0}'.format(data))
  152. self.value = self.map[data]
  153. self.key = data # pylint: disable=attribute-defined-outside-init
  154. def save(self, name: str, resp: flask.Response):
  155. """Save cookie ``name`` in the HTTP response object"""
  156. if hasattr(self, 'key'):
  157. resp.set_cookie(name, self.key, max_age=COOKIE_MAX_AGE)
  158. class BooleanSetting(Setting):
  159. """Setting of a boolean value that has to be translated in order to be storable"""
  160. def normalized_str(self, val):
  161. for v_str, v_obj in MAP_STR2BOOL.items():
  162. if val == v_obj:
  163. return v_str
  164. raise ValueError("Invalid value: %s (%s) is not a boolean!" % (repr(val), type(val)))
  165. def parse(self, data: str):
  166. """Parse and validate ``data`` and store the result at ``self.value``"""
  167. self.value = MAP_STR2BOOL[data]
  168. self.key = self.normalized_str(self.value) # pylint: disable=attribute-defined-outside-init
  169. def save(self, name: str, resp: flask.Response):
  170. """Save cookie ``name`` in the HTTP response object"""
  171. if hasattr(self, 'key'):
  172. resp.set_cookie(name, self.key, max_age=COOKIE_MAX_AGE)
  173. class BooleanChoices:
  174. """Maps strings to booleans that are either true or false."""
  175. def __init__(self, name: str, choices: Dict[str, bool], locked: bool = False):
  176. self.name = name
  177. self.choices = choices
  178. self.locked = locked
  179. self.default_choices = dict(choices)
  180. def transform_form_items(self, items):
  181. return items
  182. def transform_values(self, values):
  183. return values
  184. def parse_cookie(self, data_disabled: str, data_enabled: str):
  185. for disabled in data_disabled.split(','):
  186. if disabled in self.choices:
  187. self.choices[disabled] = False
  188. for enabled in data_enabled.split(','):
  189. if enabled in self.choices:
  190. self.choices[enabled] = True
  191. def parse_form(self, items: List[str]):
  192. if self.locked:
  193. return
  194. disabled = self.transform_form_items(items)
  195. for setting in self.choices:
  196. self.choices[setting] = setting not in disabled
  197. @property
  198. def enabled(self):
  199. return (k for k, v in self.choices.items() if v)
  200. @property
  201. def disabled(self):
  202. return (k for k, v in self.choices.items() if not v)
  203. def save(self, resp: flask.Response):
  204. """Save cookie in the HTTP response object"""
  205. disabled_changed = (k for k in self.disabled if self.default_choices[k])
  206. enabled_changed = (k for k in self.enabled if not self.default_choices[k])
  207. resp.set_cookie('disabled_{0}'.format(self.name), ','.join(disabled_changed), max_age=COOKIE_MAX_AGE)
  208. resp.set_cookie('enabled_{0}'.format(self.name), ','.join(enabled_changed), max_age=COOKIE_MAX_AGE)
  209. def get_disabled(self):
  210. return self.transform_values(list(self.disabled))
  211. def get_enabled(self):
  212. return self.transform_values(list(self.enabled))
  213. class EnginesSetting(BooleanChoices):
  214. """Engine settings"""
  215. def __init__(self, default_value, engines: Iterable[Engine]):
  216. choices = {}
  217. for engine in engines:
  218. for category in engine.categories:
  219. if not category in list(settings['categories_as_tabs'].keys()) + [DEFAULT_CATEGORY]:
  220. continue
  221. choices['{}__{}'.format(engine.name, category)] = not engine.disabled
  222. super().__init__(default_value, choices)
  223. def transform_form_items(self, items):
  224. return [item[len('engine_') :].replace('_', ' ').replace(' ', '__') for item in items]
  225. def transform_values(self, values):
  226. if len(values) == 1 and next(iter(values)) == '':
  227. return []
  228. transformed_values = []
  229. for value in values:
  230. engine, category = value.split('__')
  231. transformed_values.append((engine, category))
  232. return transformed_values
  233. class PluginsSetting(BooleanChoices):
  234. """Plugin settings"""
  235. def __init__(self, default_value, plugins: Iterable[searx.plugins.Plugin]):
  236. super().__init__(default_value, {plugin.id: plugin.default_on for plugin in plugins})
  237. def transform_form_items(self, items):
  238. return [item[len('plugin_') :] for item in items]
  239. class ClientPref:
  240. """Container to assemble client prefferences and settings."""
  241. # hint: searx.webapp.get_client_settings should be moved into this class
  242. locale: babel.Locale
  243. """Locale preferred by the client."""
  244. def __init__(self, locale: Optional[babel.Locale] = None):
  245. self.locale = locale
  246. @property
  247. def locale_tag(self):
  248. if self.locale is None:
  249. return None
  250. tag = self.locale.language
  251. if self.locale.territory:
  252. tag += '-' + self.locale.territory
  253. return tag
  254. @classmethod
  255. def from_http_request(cls, http_request: SXNG_Request):
  256. """Build ClientPref object from HTTP request.
  257. - `Accept-Language used for locale setting
  258. <https://www.w3.org/International/questions/qa-accept-lang-locales.en>`__
  259. """
  260. al_header = http_request.headers.get("Accept-Language")
  261. if not al_header:
  262. return cls(locale=None)
  263. pairs = []
  264. for l in al_header.split(','):
  265. # fmt: off
  266. lang, qvalue = [_.strip() for _ in (l.split(';') + ['q=1',])[:2]]
  267. # fmt: on
  268. try:
  269. qvalue = float(qvalue.split('=')[-1])
  270. locale = babel.Locale.parse(lang, sep='-')
  271. except (ValueError, babel.core.UnknownLocaleError):
  272. continue
  273. pairs.append((locale, qvalue))
  274. locale = None
  275. if pairs:
  276. pairs.sort(reverse=True, key=lambda x: x[1])
  277. locale = pairs[0][0]
  278. return cls(locale=locale)
  279. class Preferences:
  280. """Validates and saves preferences to cookies"""
  281. def __init__(
  282. self,
  283. themes: list[str],
  284. categories: list[str],
  285. engines: dict[str, Engine],
  286. plugins: searx.plugins.PluginStorage,
  287. client: ClientPref | None = None,
  288. ):
  289. super().__init__()
  290. self.key_value_settings: Dict[str, Setting] = {
  291. # fmt: off
  292. 'categories': MultipleChoiceSetting(
  293. ['general'],
  294. locked=is_locked('categories'),
  295. choices=categories + ['none']
  296. ),
  297. 'language': SearchLanguageSetting(
  298. settings['search']['default_lang'],
  299. locked=is_locked('language'),
  300. choices=settings['search']['languages'] + ['']
  301. ),
  302. 'locale': EnumStringSetting(
  303. settings['ui']['default_locale'],
  304. locked=is_locked('locale'),
  305. choices=list(LOCALE_NAMES.keys()) + ['']
  306. ),
  307. 'autocomplete': EnumStringSetting(
  308. settings['search']['autocomplete'],
  309. locked=is_locked('autocomplete'),
  310. choices=list(autocomplete.backends.keys()) + ['']
  311. ),
  312. 'favicon_resolver': EnumStringSetting(
  313. settings['search']['favicon_resolver'],
  314. locked=is_locked('favicon_resolver'),
  315. choices=list(favicons.proxy.CFG.resolver_map.keys()) + ['']
  316. ),
  317. 'image_proxy': BooleanSetting(
  318. settings['server']['image_proxy'],
  319. locked=is_locked('image_proxy')
  320. ),
  321. 'method': EnumStringSetting(
  322. settings['server']['method'],
  323. locked=is_locked('method'),
  324. choices=('GET', 'POST')
  325. ),
  326. 'safesearch': MapSetting(
  327. settings['search']['safe_search'],
  328. locked=is_locked('safesearch'),
  329. map={
  330. '0': 0,
  331. '1': 1,
  332. '2': 2
  333. }
  334. ),
  335. 'theme': EnumStringSetting(
  336. settings['ui']['default_theme'],
  337. locked=is_locked('theme'),
  338. choices=themes
  339. ),
  340. 'results_on_new_tab': BooleanSetting(
  341. settings['ui']['results_on_new_tab'],
  342. locked=is_locked('results_on_new_tab')
  343. ),
  344. 'doi_resolver': MultipleChoiceSetting(
  345. [settings['default_doi_resolver'], ],
  346. locked=is_locked('doi_resolver'),
  347. choices=DOI_RESOLVERS
  348. ),
  349. 'simple_style': EnumStringSetting(
  350. settings['ui']['theme_args']['simple_style'],
  351. locked=is_locked('simple_style'),
  352. choices=['', 'auto', 'light', 'dark', 'black']
  353. ),
  354. 'center_alignment': BooleanSetting(
  355. settings['ui']['center_alignment'],
  356. locked=is_locked('center_alignment')
  357. ),
  358. 'advanced_search': BooleanSetting(
  359. settings['ui']['advanced_search'],
  360. locked=is_locked('advanced_search')
  361. ),
  362. 'query_in_title': BooleanSetting(
  363. settings['ui']['query_in_title'],
  364. locked=is_locked('query_in_title')
  365. ),
  366. 'infinite_scroll': BooleanSetting(
  367. settings['ui']['infinite_scroll'],
  368. locked=is_locked('infinite_scroll')
  369. ),
  370. 'search_on_category_select': BooleanSetting(
  371. settings['ui']['search_on_category_select'],
  372. locked=is_locked('search_on_category_select')
  373. ),
  374. 'hotkeys': EnumStringSetting(
  375. settings['ui']['hotkeys'],
  376. choices=['default', 'vim']
  377. ),
  378. 'url_formatting': EnumStringSetting(
  379. settings['ui']['url_formatting'],
  380. choices=['pretty', 'full', 'host']
  381. ),
  382. # fmt: on
  383. }
  384. self.engines = EnginesSetting('engines', engines=engines.values())
  385. self.plugins = PluginsSetting('plugins', plugins=plugins)
  386. self.tokens = SetSetting('tokens')
  387. self.client = client or ClientPref()
  388. def get_as_url_params(self):
  389. """Return preferences as URL parameters"""
  390. settings_kv = {}
  391. for k, v in self.key_value_settings.items():
  392. if v.locked:
  393. continue
  394. if isinstance(v, MultipleChoiceSetting):
  395. settings_kv[k] = ','.join(v.get_value())
  396. else:
  397. settings_kv[k] = v.get_value()
  398. settings_kv['disabled_engines'] = ','.join(self.engines.disabled)
  399. settings_kv['enabled_engines'] = ','.join(self.engines.enabled)
  400. settings_kv['disabled_plugins'] = ','.join(self.plugins.disabled)
  401. settings_kv['enabled_plugins'] = ','.join(self.plugins.enabled)
  402. settings_kv['tokens'] = ','.join(self.tokens.values)
  403. return urlsafe_b64encode(compress(urlencode(settings_kv).encode())).decode()
  404. def parse_encoded_data(self, input_data: str):
  405. """parse (base64) preferences from request (``flask.request.form['preferences']``)"""
  406. bin_data = decompress(urlsafe_b64decode(input_data))
  407. dict_data = {}
  408. for x, y in parse_qs(bin_data.decode('ascii'), keep_blank_values=True).items():
  409. dict_data[x] = y[0]
  410. self.parse_dict(dict_data)
  411. def parse_dict(self, input_data: Dict[str, str]):
  412. """parse preferences from request (``flask.request.form``)"""
  413. for user_setting_name, user_setting in input_data.items():
  414. if user_setting_name in self.key_value_settings:
  415. if self.key_value_settings[user_setting_name].locked:
  416. continue
  417. self.key_value_settings[user_setting_name].parse(user_setting)
  418. elif user_setting_name == 'disabled_engines':
  419. self.engines.parse_cookie(input_data.get('disabled_engines', ''), input_data.get('enabled_engines', ''))
  420. elif user_setting_name == 'disabled_plugins':
  421. self.plugins.parse_cookie(input_data.get('disabled_plugins', ''), input_data.get('enabled_plugins', ''))
  422. elif user_setting_name == 'tokens':
  423. self.tokens.parse(user_setting)
  424. def parse_form(self, input_data: Dict[str, str]):
  425. """Parse formular (``<input>``) data from a ``flask.request.form``"""
  426. disabled_engines = []
  427. enabled_categories = []
  428. disabled_plugins = []
  429. # boolean preferences are not sent by the form if they're false,
  430. # so we have to add them as false manually if they're not sent (then they would be true)
  431. for key, setting in self.key_value_settings.items():
  432. if key not in input_data.keys() and isinstance(setting, BooleanSetting):
  433. input_data[key] = 'False'
  434. for user_setting_name, user_setting in input_data.items():
  435. if user_setting_name in self.key_value_settings:
  436. self.key_value_settings[user_setting_name].parse(user_setting)
  437. elif user_setting_name.startswith('engine_'):
  438. disabled_engines.append(user_setting_name)
  439. elif user_setting_name.startswith('category_'):
  440. enabled_categories.append(user_setting_name[len('category_') :])
  441. elif user_setting_name.startswith('plugin_'):
  442. disabled_plugins.append(user_setting_name)
  443. elif user_setting_name == 'tokens':
  444. self.tokens.parse_form(user_setting)
  445. self.key_value_settings['categories'].parse_form(enabled_categories)
  446. self.engines.parse_form(disabled_engines)
  447. self.plugins.parse_form(disabled_plugins)
  448. # cannot be used in case of engines or plugins
  449. def get_value(self, user_setting_name: str):
  450. """Returns the value for ``user_setting_name``"""
  451. ret_val = None
  452. if user_setting_name in self.key_value_settings:
  453. ret_val = self.key_value_settings[user_setting_name].get_value()
  454. return ret_val
  455. def save(self, resp: flask.Response):
  456. """Save cookie in the HTTP response object"""
  457. for user_setting_name, user_setting in self.key_value_settings.items():
  458. # pylint: disable=unnecessary-dict-index-lookup
  459. if self.key_value_settings[user_setting_name].locked:
  460. continue
  461. user_setting.save(user_setting_name, resp)
  462. self.engines.save(resp)
  463. self.plugins.save(resp)
  464. self.tokens.save('tokens', resp)
  465. return resp
  466. def validate_token(self, engine):
  467. valid = True
  468. if hasattr(engine, 'tokens') and engine.tokens:
  469. valid = False
  470. for token in self.tokens.values:
  471. if token in engine.tokens:
  472. valid = True
  473. break
  474. return valid
  475. def is_locked(setting_name: str):
  476. """Checks if a given setting name is locked by settings.yml"""
  477. if 'preferences' not in settings:
  478. return False
  479. if 'lock' not in settings['preferences']:
  480. return False
  481. return setting_name in settings['preferences']['lock']