preferences.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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 reponse obect
  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 reponse obect
  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 reponse obect
  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('-')[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 reponse obect
  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. # pylint: disable=no-self-use
  171. return items
  172. def transform_values(self, values): # pylint: disable=missing-function-docstring
  173. # pylint: disable=no-self-use
  174. return values
  175. def parse_cookie(self, data): # pylint: disable=missing-function-docstring
  176. # pylint: disable=attribute-defined-outside-init
  177. if data[DISABLED] != '':
  178. self.disabled = set(data[DISABLED].split(','))
  179. if data[ENABLED] != '':
  180. self.enabled = set(data[ENABLED].split(','))
  181. def parse_form(self, items): # pylint: disable=missing-function-docstring
  182. if self.locked:
  183. return
  184. items = self.transform_form_items(items)
  185. self.disabled = set() # pylint: disable=attribute-defined-outside-init
  186. self.enabled = set() # pylint: disable=attribute-defined-outside-init
  187. for choice in self.choices: # pylint: disable=no-member
  188. if choice['default_on']:
  189. if choice['id'] in items:
  190. self.disabled.add(choice['id'])
  191. else:
  192. if choice['id'] not in items:
  193. self.enabled.add(choice['id'])
  194. def save(self, resp): # pylint: disable=arguments-differ
  195. """Save cookie in the HTTP reponse obect
  196. """
  197. resp.set_cookie('disabled_{0}'.format(self.value), ','.join(self.disabled), max_age=COOKIE_MAX_AGE)
  198. resp.set_cookie('enabled_{0}'.format(self.value), ','.join(self.enabled), max_age=COOKIE_MAX_AGE)
  199. def get_disabled(self): # pylint: disable=missing-function-docstring
  200. disabled = self.disabled
  201. for choice in self.choices: # pylint: disable=no-member
  202. if not choice['default_on'] and choice['id'] not in self.enabled:
  203. disabled.add(choice['id'])
  204. return self.transform_values(disabled)
  205. def get_enabled(self): # pylint: disable=missing-function-docstring
  206. enabled = self.enabled
  207. for choice in self.choices: # pylint: disable=no-member
  208. if choice['default_on'] and choice['id'] not in self.disabled:
  209. enabled.add(choice['id'])
  210. return self.transform_values(enabled)
  211. class EnginesSetting(SwitchableSetting):
  212. """Engine settings"""
  213. def _post_init(self):
  214. super()._post_init()
  215. transformed_choices = []
  216. for engine_name, engine in self.choices.items(): # pylint: disable=no-member,access-member-before-definition
  217. for category in engine.categories:
  218. transformed_choice = dict()
  219. transformed_choice['default_on'] = not engine.disabled
  220. transformed_choice['id'] = '{}__{}'.format(engine_name, category)
  221. transformed_choices.append(transformed_choice)
  222. self.choices = transformed_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 list()
  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(SwitchableSetting):
  234. """Plugin settings"""
  235. def _post_init(self):
  236. super()._post_init()
  237. transformed_choices = []
  238. for plugin in self.choices: # pylint: disable=access-member-before-definition
  239. transformed_choice = dict()
  240. transformed_choice['default_on'] = plugin.default_on
  241. transformed_choice['id'] = plugin.id
  242. transformed_choices.append(transformed_choice)
  243. self.choices = transformed_choices
  244. def transform_form_items(self, items):
  245. return [item[len('plugin_'):] for item in items]
  246. class Preferences:
  247. """Validates and saves preferences to cookies"""
  248. def __init__(self, themes, categories, engines, plugins):
  249. super().__init__()
  250. self.key_value_settings = {
  251. 'categories': MultipleChoiceSetting(
  252. ['general'],
  253. is_locked('categories'),
  254. choices=categories + ['none']
  255. ),
  256. 'language': SearchLanguageSetting(
  257. settings['search'].get('default_lang', ''),
  258. is_locked('language'),
  259. choices=list(LANGUAGE_CODES) + ['']
  260. ),
  261. 'locale': EnumStringSetting(
  262. settings['ui'].get('default_locale', ''),
  263. is_locked('locale'),
  264. choices=list(settings['locales'].keys()) + ['']
  265. ),
  266. 'autocomplete': EnumStringSetting(
  267. settings['search'].get('autocomplete', ''),
  268. is_locked('autocomplete'),
  269. choices=list(autocomplete.backends.keys()) + ['']
  270. ),
  271. 'image_proxy': MapSetting(
  272. settings['server'].get('image_proxy', False),
  273. is_locked('image_proxy'),
  274. map={
  275. '': settings['server'].get('image_proxy', 0),
  276. '0': False,
  277. '1': True,
  278. 'True': True,
  279. 'False': False
  280. }
  281. ),
  282. 'method': EnumStringSetting(
  283. settings['server'].get('method', 'POST'),
  284. is_locked('method'),
  285. choices=('GET', 'POST')
  286. ),
  287. 'safesearch': MapSetting(
  288. settings['search'].get('safe_search', 0),
  289. is_locked('safesearch'),
  290. map={
  291. '0': 0,
  292. '1': 1,
  293. '2': 2
  294. }
  295. ),
  296. 'theme': EnumStringSetting(
  297. settings['ui'].get('default_theme', 'oscar'),
  298. is_locked('theme'),
  299. choices=themes
  300. ),
  301. 'results_on_new_tab': MapSetting(
  302. settings['ui'].get('results_on_new_tab', False),
  303. is_locked('results_on_new_tab'),
  304. map={
  305. '0': False,
  306. '1': True,
  307. 'False': False,
  308. 'True': True
  309. }
  310. ),
  311. 'doi_resolver': MultipleChoiceSetting(
  312. ['oadoi.org'],
  313. is_locked('doi_resolver'),
  314. choices=DOI_RESOLVERS
  315. ),
  316. 'oscar-style': EnumStringSetting(
  317. settings['ui'].get('theme_args', {}).get('oscar_style', 'logicodev'),
  318. is_locked('oscar-style'),
  319. choices=['', 'logicodev', 'logicodev-dark', 'pointhi']),
  320. 'advanced_search': MapSetting(
  321. settings['ui'].get('advanced_search', False),
  322. is_locked('advanced_search'),
  323. map={
  324. '0': False,
  325. '1': True,
  326. 'False': False,
  327. 'True': True,
  328. 'on': True,
  329. }
  330. ),
  331. }
  332. self.engines = EnginesSetting('engines', choices=engines)
  333. self.plugins = PluginsSetting('plugins', choices=plugins)
  334. self.tokens = SetSetting('tokens')
  335. self.unknown_params = {}
  336. def get_as_url_params(self):
  337. """Return preferences as URL parameters"""
  338. settings_kv = {}
  339. for k, v in self.key_value_settings.items():
  340. if v.locked:
  341. continue
  342. if isinstance(v, MultipleChoiceSetting):
  343. settings_kv[k] = ','.join(v.get_value())
  344. else:
  345. settings_kv[k] = v.get_value()
  346. settings_kv['disabled_engines'] = ','.join(self.engines.disabled)
  347. settings_kv['enabled_engines'] = ','.join(self.engines.enabled)
  348. settings_kv['disabled_plugins'] = ','.join(self.plugins.disabled)
  349. settings_kv['enabled_plugins'] = ','.join(self.plugins.enabled)
  350. settings_kv['tokens'] = ','.join(self.tokens.values)
  351. return urlsafe_b64encode(compress(urlencode(settings_kv).encode())).decode()
  352. def parse_encoded_data(self, input_data):
  353. """parse (base64) preferences from request (``flask.request.form['preferences']``)"""
  354. decoded_data = decompress(urlsafe_b64decode(input_data.encode()))
  355. dict_data = {}
  356. for x, y in parse_qs(decoded_data).items():
  357. dict_data[x.decode()] = y[0].decode()
  358. self.parse_dict(dict_data)
  359. def parse_dict(self, input_data):
  360. """parse preferences from request (``flask.request.form``)"""
  361. for user_setting_name, user_setting in input_data.items():
  362. if user_setting_name in self.key_value_settings:
  363. if self.key_value_settings[user_setting_name].locked:
  364. continue
  365. self.key_value_settings[user_setting_name].parse(user_setting)
  366. elif user_setting_name == 'disabled_engines':
  367. self.engines.parse_cookie((input_data.get('disabled_engines', ''),
  368. input_data.get('enabled_engines', '')))
  369. elif user_setting_name == 'disabled_plugins':
  370. self.plugins.parse_cookie((input_data.get('disabled_plugins', ''),
  371. input_data.get('enabled_plugins', '')))
  372. elif user_setting_name == 'tokens':
  373. self.tokens.parse(user_setting)
  374. elif not any(user_setting_name.startswith(x) for x in [
  375. 'enabled_',
  376. 'disabled_',
  377. 'engine_',
  378. 'category_',
  379. 'plugin_']):
  380. self.unknown_params[user_setting_name] = user_setting
  381. def parse_form(self, input_data):
  382. """Parse formular (``<input>``) data from a ``flask.request.form``"""
  383. disabled_engines = []
  384. enabled_categories = []
  385. disabled_plugins = []
  386. for user_setting_name, user_setting in input_data.items():
  387. if user_setting_name in self.key_value_settings:
  388. self.key_value_settings[user_setting_name].parse(user_setting)
  389. elif user_setting_name.startswith('engine_'):
  390. disabled_engines.append(user_setting_name)
  391. elif user_setting_name.startswith('category_'):
  392. enabled_categories.append(user_setting_name[len('category_'):])
  393. elif user_setting_name.startswith('plugin_'):
  394. disabled_plugins.append(user_setting_name)
  395. elif user_setting_name == 'tokens':
  396. self.tokens.parse_form(user_setting)
  397. else:
  398. self.unknown_params[user_setting_name] = user_setting
  399. self.key_value_settings['categories'].parse_form(enabled_categories)
  400. self.engines.parse_form(disabled_engines)
  401. self.plugins.parse_form(disabled_plugins)
  402. # cannot be used in case of engines or plugins
  403. def get_value(self, user_setting_name):
  404. """Returns the value for ``user_setting_name``
  405. """
  406. ret_val = None
  407. if user_setting_name in self.key_value_settings:
  408. ret_val = self.key_value_settings[user_setting_name].get_value()
  409. if user_setting_name in self.unknown_params:
  410. ret_val = self.unknown_params[user_setting_name]
  411. return ret_val
  412. def save(self, resp):
  413. """Save cookie in the HTTP reponse obect
  414. """
  415. for user_setting_name, user_setting in self.key_value_settings.items():
  416. if self.key_value_settings[user_setting_name].locked:
  417. continue
  418. user_setting.save(user_setting_name, resp)
  419. self.engines.save(resp)
  420. self.plugins.save(resp)
  421. self.tokens.save('tokens', resp)
  422. for k, v in self.unknown_params.items():
  423. resp.set_cookie(k, v, max_age=COOKIE_MAX_AGE)
  424. return resp
  425. def validate_token(self, engine): # pylint: disable=missing-function-docstring
  426. valid = True
  427. if hasattr(engine, 'tokens') and engine.tokens:
  428. valid = False
  429. for token in self.tokens.values:
  430. if token in engine.tokens:
  431. valid = True
  432. break
  433. return valid
  434. def is_locked(setting_name):
  435. """Checks if a given setting name is locked by settings.yml
  436. """
  437. if 'preferences' not in settings:
  438. return False
  439. if 'lock' not in settings['preferences']:
  440. return False
  441. return setting_name in settings['preferences']['lock']