preferences.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Searx preferences implementation.
  3. """
  4. # pylint: disable=useless-object-inheritance
  5. from base64 import urlsafe_b64encode, urlsafe_b64decode
  6. from zlib import compress, decompress
  7. from urllib.parse import parse_qs, urlencode
  8. from searx import settings, autocomplete
  9. from searx.languages import language_codes as languages
  10. from searx.webutils import VALID_LANGUAGE_CODE
  11. COOKIE_MAX_AGE = 60 * 60 * 24 * 365 * 5 # 5 years
  12. LANGUAGE_CODES = [l[0] for l in languages]
  13. LANGUAGE_CODES.append('all')
  14. DISABLED = 0
  15. ENABLED = 1
  16. DOI_RESOLVERS = list(settings['doi_resolvers'])
  17. class MissingArgumentException(Exception):
  18. """Exption from ``cls._post_init`` when a argument is missed.
  19. """
  20. class ValidationException(Exception):
  21. """Exption from ``cls._post_init`` when configuration value is invalid.
  22. """
  23. class Setting:
  24. """Base class of user settings"""
  25. def __init__(self, default_value, locked=False, **kwargs):
  26. super().__init__()
  27. self.value = default_value
  28. self.locked = locked
  29. for key, value in kwargs.items():
  30. setattr(self, key, value)
  31. self._post_init()
  32. def _post_init(self):
  33. pass
  34. def parse(self, data):
  35. """Parse ``data`` and store the result at ``self.value``
  36. If needed, its overwritten in the inheritance.
  37. """
  38. self.value = data
  39. def get_value(self):
  40. """Returns the value of the setting
  41. If needed, its overwritten in the inheritance.
  42. """
  43. return self.value
  44. def save(self, name, resp):
  45. """Save cookie ``name`` in the HTTP response object
  46. If needed, its overwritten in the inheritance."""
  47. resp.set_cookie(name, self.value, max_age=COOKIE_MAX_AGE)
  48. class StringSetting(Setting):
  49. """Setting of plain string values"""
  50. class EnumStringSetting(Setting):
  51. """Setting of a value which can only come from the given choices"""
  52. def _post_init(self):
  53. if not hasattr(self, 'choices'):
  54. raise MissingArgumentException('Missing argument: choices')
  55. self._validate_selection(self.value)
  56. def _validate_selection(self, selection):
  57. if selection not in self.choices: # pylint: disable=no-member
  58. raise ValidationException('Invalid value: "{0}"'.format(selection))
  59. def parse(self, data):
  60. """Parse and validate ``data`` and store the result at ``self.value``
  61. """
  62. self._validate_selection(data)
  63. self.value = data
  64. class MultipleChoiceSetting(EnumStringSetting):
  65. """Setting of values which can only come from the given choices"""
  66. def _validate_selections(self, selections):
  67. for item in selections:
  68. if item not in self.choices: # pylint: disable=no-member
  69. raise ValidationException('Invalid value: "{0}"'.format(selections))
  70. def _post_init(self):
  71. if not hasattr(self, 'choices'):
  72. raise MissingArgumentException('Missing argument: choices')
  73. self._validate_selections(self.value)
  74. def parse(self, data):
  75. """Parse and validate ``data`` and store the result at ``self.value``
  76. """
  77. if data == '':
  78. self.value = []
  79. return
  80. elements = data.split(',')
  81. self._validate_selections(elements)
  82. self.value = elements
  83. def parse_form(self, data): # pylint: disable=missing-function-docstring
  84. if self.locked:
  85. return
  86. self.value = []
  87. for choice in data:
  88. if choice in self.choices and choice not in self.value: # pylint: disable=no-member
  89. self.value.append(choice)
  90. def save(self, name, resp):
  91. """Save cookie ``name`` in the HTTP response object
  92. """
  93. resp.set_cookie(name, ','.join(self.value), max_age=COOKIE_MAX_AGE)
  94. class SetSetting(Setting):
  95. """Setting of values of type ``set`` (comma separated string) """
  96. def _post_init(self):
  97. if not hasattr(self, 'values'):
  98. self.values = set()
  99. def get_value(self):
  100. """Returns a string with comma separated values.
  101. """
  102. return ','.join(self.values)
  103. def parse(self, data):
  104. """Parse and validate ``data`` and store the result at ``self.value``
  105. """
  106. if data == '':
  107. self.values = set() # pylint: disable=attribute-defined-outside-init
  108. return
  109. elements = data.split(',')
  110. for element in elements:
  111. self.values.add(element)
  112. def parse_form(self, data): # pylint: disable=missing-function-docstring
  113. if self.locked:
  114. return
  115. elements = data.split(',')
  116. self.values = set(elements) # pylint: disable=attribute-defined-outside-init
  117. def save(self, name, resp):
  118. """Save cookie ``name`` in the HTTP response object
  119. """
  120. resp.set_cookie(name, ','.join(self.values), max_age=COOKIE_MAX_AGE)
  121. class SearchLanguageSetting(EnumStringSetting):
  122. """Available choices may change, so user's value may not be in choices anymore"""
  123. def _validate_selection(self, selection):
  124. if selection != '' and not VALID_LANGUAGE_CODE.match(selection):
  125. raise ValidationException('Invalid language code: "{0}"'.format(selection))
  126. def parse(self, data):
  127. """Parse and validate ``data`` and store the result at ``self.value``
  128. """
  129. if data not in self.choices and data != self.value: # pylint: disable=no-member
  130. # hack to give some backwards compatibility with old language cookies
  131. data = str(data).replace('_', '-')
  132. lang = data.split('-', maxsplit=1)[0]
  133. # pylint: disable=no-member
  134. if data in self.choices:
  135. pass
  136. elif lang in self.choices:
  137. data = lang
  138. else:
  139. data = self.value
  140. self._validate_selection(data)
  141. self.value = data
  142. class MapSetting(Setting):
  143. """Setting of a value that has to be translated in order to be storable"""
  144. def _post_init(self):
  145. if not hasattr(self, 'map'):
  146. raise MissingArgumentException('missing argument: map')
  147. if self.value not in self.map.values(): # pylint: disable=no-member
  148. raise ValidationException('Invalid default value')
  149. def parse(self, data):
  150. """Parse and validate ``data`` and store the result at ``self.value``
  151. """
  152. # pylint: disable=no-member
  153. if data not in self.map:
  154. raise ValidationException('Invalid choice: {0}'.format(data))
  155. self.value = self.map[data]
  156. self.key = data # pylint: disable=attribute-defined-outside-init
  157. def save(self, name, resp):
  158. """Save cookie ``name`` in the HTTP response object
  159. """
  160. if hasattr(self, 'key'):
  161. resp.set_cookie(name, self.key, max_age=COOKIE_MAX_AGE)
  162. class SwitchableSetting(Setting):
  163. """ Base class for settings that can be turned on && off"""
  164. def _post_init(self):
  165. self.disabled = set()
  166. self.enabled = set()
  167. if not hasattr(self, 'choices'):
  168. raise MissingArgumentException('missing argument: choices')
  169. def transform_form_items(self, items): # pylint: disable=missing-function-docstring
  170. return items
  171. def transform_values(self, values): # pylint: disable=missing-function-docstring
  172. return values
  173. def parse_cookie(self, data): # pylint: disable=missing-function-docstring
  174. # pylint: disable=attribute-defined-outside-init
  175. if data[DISABLED] != '':
  176. self.disabled = set(data[DISABLED].split(','))
  177. if data[ENABLED] != '':
  178. self.enabled = set(data[ENABLED].split(','))
  179. def parse_form(self, items): # pylint: disable=missing-function-docstring
  180. if self.locked:
  181. return
  182. items = self.transform_form_items(items)
  183. self.disabled = set() # pylint: disable=attribute-defined-outside-init
  184. self.enabled = set() # pylint: disable=attribute-defined-outside-init
  185. for choice in self.choices: # pylint: disable=no-member
  186. if choice['default_on']:
  187. if choice['id'] in items:
  188. self.disabled.add(choice['id'])
  189. else:
  190. if choice['id'] not in items:
  191. self.enabled.add(choice['id'])
  192. def save(self, resp): # pylint: disable=arguments-differ
  193. """Save cookie in the HTTP response object
  194. """
  195. resp.set_cookie('disabled_{0}'.format(self.value), ','.join(self.disabled), max_age=COOKIE_MAX_AGE)
  196. resp.set_cookie('enabled_{0}'.format(self.value), ','.join(self.enabled), max_age=COOKIE_MAX_AGE)
  197. def get_disabled(self): # pylint: disable=missing-function-docstring
  198. disabled = self.disabled
  199. for choice in self.choices: # pylint: disable=no-member
  200. if not choice['default_on'] and choice['id'] not in self.enabled:
  201. disabled.add(choice['id'])
  202. return self.transform_values(disabled)
  203. def get_enabled(self): # pylint: disable=missing-function-docstring
  204. enabled = self.enabled
  205. for choice in self.choices: # pylint: disable=no-member
  206. if choice['default_on'] and choice['id'] not in self.disabled:
  207. enabled.add(choice['id'])
  208. return self.transform_values(enabled)
  209. class EnginesSetting(SwitchableSetting):
  210. """Engine settings"""
  211. def _post_init(self):
  212. super()._post_init()
  213. transformed_choices = []
  214. for engine_name, engine in self.choices.items(): # pylint: disable=no-member,access-member-before-definition
  215. for category in engine.categories:
  216. transformed_choice = {}
  217. transformed_choice['default_on'] = not engine.disabled
  218. transformed_choice['id'] = '{}__{}'.format(engine_name, category)
  219. transformed_choices.append(transformed_choice)
  220. self.choices = transformed_choices
  221. def transform_form_items(self, items):
  222. return [item[len('engine_'):].replace('_', ' ').replace(' ', '__') for item in items]
  223. def transform_values(self, values):
  224. if len(values) == 1 and next(iter(values)) == '':
  225. return []
  226. transformed_values = []
  227. for value in values:
  228. engine, category = value.split('__')
  229. transformed_values.append((engine, category))
  230. return transformed_values
  231. class PluginsSetting(SwitchableSetting):
  232. """Plugin settings"""
  233. def _post_init(self):
  234. super()._post_init()
  235. transformed_choices = []
  236. for plugin in self.choices: # pylint: disable=access-member-before-definition
  237. transformed_choice = {}
  238. transformed_choice['default_on'] = plugin.default_on
  239. transformed_choice['id'] = plugin.id
  240. transformed_choices.append(transformed_choice)
  241. self.choices = transformed_choices
  242. def transform_form_items(self, items):
  243. return [item[len('plugin_'):] for item in items]
  244. class Preferences:
  245. """Validates and saves preferences to cookies"""
  246. def __init__(self, themes, categories, engines, plugins):
  247. super().__init__()
  248. self.key_value_settings = {
  249. 'categories': MultipleChoiceSetting(
  250. ['general'],
  251. is_locked('categories'),
  252. choices=categories + ['none']
  253. ),
  254. 'language': SearchLanguageSetting(
  255. settings['search'].get('default_lang', ''),
  256. is_locked('language'),
  257. choices=list(LANGUAGE_CODES) + ['']
  258. ),
  259. 'locale': EnumStringSetting(
  260. settings['ui'].get('default_locale', ''),
  261. is_locked('locale'),
  262. choices=list(settings['locales'].keys()) + ['']
  263. ),
  264. 'autocomplete': EnumStringSetting(
  265. settings['search'].get('autocomplete', ''),
  266. is_locked('autocomplete'),
  267. choices=list(autocomplete.backends.keys()) + ['']
  268. ),
  269. 'autofocus': MapSetting(
  270. settings['ui'].get('autofocus', True),
  271. is_locked('autofocus'),
  272. map={
  273. '0': False,
  274. '1': True,
  275. 'False': False,
  276. 'True': True
  277. }
  278. ),
  279. 'archive_today': MapSetting(
  280. settings['ui'].get('archive_today', True),
  281. is_locked('archive_today'),
  282. map={
  283. '0': False,
  284. '1': True,
  285. 'False': False,
  286. 'True': True
  287. }
  288. ),
  289. 'image_proxy': MapSetting(
  290. settings['server'].get('image_proxy', False),
  291. is_locked('image_proxy'),
  292. map={
  293. '': settings['server'].get('image_proxy', 0),
  294. '0': False,
  295. '1': True,
  296. 'True': True,
  297. 'False': False
  298. }
  299. ),
  300. 'method': EnumStringSetting(
  301. settings['server'].get('method', 'POST'),
  302. is_locked('method'),
  303. choices=('GET', 'POST')
  304. ),
  305. 'safesearch': MapSetting(
  306. settings['search'].get('safe_search', 0),
  307. is_locked('safesearch'),
  308. map={
  309. '0': 0,
  310. '1': 1,
  311. '2': 2
  312. }
  313. ),
  314. 'theme': EnumStringSetting(
  315. settings['ui'].get('default_theme', 'oscar'),
  316. is_locked('theme'),
  317. choices=themes
  318. ),
  319. 'results_on_new_tab': MapSetting(
  320. settings['ui'].get('results_on_new_tab', False),
  321. is_locked('results_on_new_tab'),
  322. map={
  323. '0': False,
  324. '1': True,
  325. 'False': False,
  326. 'True': True
  327. }
  328. ),
  329. 'doi_resolver': MultipleChoiceSetting(
  330. [settings['default_doi_resolver'], ],
  331. is_locked('doi_resolver'),
  332. choices=DOI_RESOLVERS
  333. ),
  334. 'oscar-style': EnumStringSetting(
  335. settings['ui'].get('theme_args', {}).get('oscar_style', 'logicodev'),
  336. is_locked('oscar-style'),
  337. choices=['', 'logicodev', 'logicodev-dark', 'pointhi']),
  338. 'advanced_search': MapSetting(
  339. settings['ui'].get('advanced_search', False),
  340. is_locked('advanced_search'),
  341. map={
  342. '0': False,
  343. '1': True,
  344. 'False': False,
  345. 'True': True,
  346. 'on': True,
  347. }
  348. ),
  349. }
  350. self.engines = EnginesSetting('engines', choices=engines)
  351. self.plugins = PluginsSetting('plugins', choices=plugins)
  352. self.tokens = SetSetting('tokens')
  353. self.unknown_params = {}
  354. def get_as_url_params(self):
  355. """Return preferences as URL parameters"""
  356. settings_kv = {}
  357. for k, v in self.key_value_settings.items():
  358. if v.locked:
  359. continue
  360. if isinstance(v, MultipleChoiceSetting):
  361. settings_kv[k] = ','.join(v.get_value())
  362. else:
  363. settings_kv[k] = v.get_value()
  364. settings_kv['disabled_engines'] = ','.join(self.engines.disabled)
  365. settings_kv['enabled_engines'] = ','.join(self.engines.enabled)
  366. settings_kv['disabled_plugins'] = ','.join(self.plugins.disabled)
  367. settings_kv['enabled_plugins'] = ','.join(self.plugins.enabled)
  368. settings_kv['tokens'] = ','.join(self.tokens.values)
  369. return urlsafe_b64encode(compress(urlencode(settings_kv).encode())).decode()
  370. def parse_encoded_data(self, input_data):
  371. """parse (base64) preferences from request (``flask.request.form['preferences']``)"""
  372. decoded_data = decompress(urlsafe_b64decode(input_data.encode()))
  373. dict_data = {}
  374. for x, y in parse_qs(decoded_data.decode()).items():
  375. dict_data[x] = y[0]
  376. self.parse_dict(dict_data)
  377. def parse_dict(self, input_data):
  378. """parse preferences from request (``flask.request.form``)"""
  379. for user_setting_name, user_setting in input_data.items():
  380. if user_setting_name in self.key_value_settings:
  381. if self.key_value_settings[user_setting_name].locked:
  382. continue
  383. self.key_value_settings[user_setting_name].parse(user_setting)
  384. elif user_setting_name == 'disabled_engines':
  385. self.engines.parse_cookie((input_data.get('disabled_engines', ''),
  386. input_data.get('enabled_engines', '')))
  387. elif user_setting_name == 'disabled_plugins':
  388. self.plugins.parse_cookie((input_data.get('disabled_plugins', ''),
  389. input_data.get('enabled_plugins', '')))
  390. elif user_setting_name == 'tokens':
  391. self.tokens.parse(user_setting)
  392. elif not any(user_setting_name.startswith(x) for x in [
  393. 'enabled_',
  394. 'disabled_',
  395. 'engine_',
  396. 'category_',
  397. 'plugin_']):
  398. self.unknown_params[user_setting_name] = user_setting
  399. def parse_form(self, input_data):
  400. """Parse formular (``<input>``) data from a ``flask.request.form``"""
  401. disabled_engines = []
  402. enabled_categories = []
  403. disabled_plugins = []
  404. for user_setting_name, user_setting in input_data.items():
  405. if user_setting_name in self.key_value_settings:
  406. self.key_value_settings[user_setting_name].parse(user_setting)
  407. elif user_setting_name.startswith('engine_'):
  408. disabled_engines.append(user_setting_name)
  409. elif user_setting_name.startswith('category_'):
  410. enabled_categories.append(user_setting_name[len('category_'):])
  411. elif user_setting_name.startswith('plugin_'):
  412. disabled_plugins.append(user_setting_name)
  413. elif user_setting_name == 'tokens':
  414. self.tokens.parse_form(user_setting)
  415. else:
  416. self.unknown_params[user_setting_name] = user_setting
  417. self.key_value_settings['categories'].parse_form(enabled_categories)
  418. self.engines.parse_form(disabled_engines)
  419. self.plugins.parse_form(disabled_plugins)
  420. # cannot be used in case of engines or plugins
  421. def get_value(self, user_setting_name):
  422. """Returns the value for ``user_setting_name``
  423. """
  424. ret_val = None
  425. if user_setting_name in self.key_value_settings:
  426. ret_val = self.key_value_settings[user_setting_name].get_value()
  427. if user_setting_name in self.unknown_params:
  428. ret_val = self.unknown_params[user_setting_name]
  429. return ret_val
  430. def save(self, resp):
  431. """Save cookie in the HTTP response object
  432. """
  433. for user_setting_name, user_setting in self.key_value_settings.items():
  434. if user_setting.locked:
  435. continue
  436. user_setting.save(user_setting_name, resp)
  437. self.engines.save(resp)
  438. self.plugins.save(resp)
  439. self.tokens.save('tokens', resp)
  440. for k, v in self.unknown_params.items():
  441. resp.set_cookie(k, v, max_age=COOKIE_MAX_AGE)
  442. return resp
  443. def validate_token(self, engine): # pylint: disable=missing-function-docstring
  444. valid = True
  445. if hasattr(engine, 'tokens') and engine.tokens:
  446. valid = False
  447. for token in self.tokens.values:
  448. if token in engine.tokens:
  449. valid = True
  450. break
  451. return valid
  452. def is_locked(setting_name):
  453. """Checks if a given setting name is locked by settings.yml
  454. """
  455. if 'preferences' not in settings:
  456. return False
  457. if 'lock' not in settings['preferences']:
  458. return False
  459. return setting_name in settings['preferences']['lock']