2020-02-23 19:52:00 +00:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
"""Searx preferences implementation.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# pylint: disable=useless-object-inheritance
|
|
|
|
|
2017-10-25 21:56:37 +00:00
|
|
|
from base64 import urlsafe_b64encode, urlsafe_b64decode
|
|
|
|
from zlib import compress, decompress
|
2020-08-06 15:42:46 +00:00
|
|
|
from urllib.parse import parse_qs, urlencode
|
2023-01-30 17:40:22 +00:00
|
|
|
from typing import Iterable, Dict, List, Optional
|
2023-08-22 13:35:46 +00:00
|
|
|
from collections import OrderedDict
|
2022-01-04 10:53:42 +00:00
|
|
|
|
|
|
|
import flask
|
2023-01-30 17:40:22 +00:00
|
|
|
import babel
|
2017-10-25 21:56:37 +00:00
|
|
|
|
2024-08-19 15:47:54 +00:00
|
|
|
from searx import settings, autocomplete, favicons
|
2022-09-29 18:54:46 +00:00
|
|
|
from searx.enginelib import Engine
|
2022-01-04 10:53:42 +00:00
|
|
|
from searx.plugins import Plugin
|
2021-08-03 13:13:00 +00:00
|
|
|
from searx.locales import LOCALE_NAMES
|
2020-10-01 09:29:31 +00:00
|
|
|
from searx.webutils import VALID_LANGUAGE_CODE
|
2022-07-24 07:32:05 +00:00
|
|
|
from searx.engines import DEFAULT_CATEGORY
|
2016-04-08 14:38:05 +00:00
|
|
|
|
|
|
|
|
|
|
|
COOKIE_MAX_AGE = 60 * 60 * 24 * 365 * 5 # 5 years
|
2017-11-01 12:58:48 +00:00
|
|
|
DOI_RESOLVERS = list(settings['doi_resolvers'])
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2023-08-22 13:35:46 +00:00
|
|
|
MAP_STR2BOOL: Dict[str, bool] = OrderedDict(
|
|
|
|
[
|
|
|
|
('0', False),
|
|
|
|
('1', True),
|
|
|
|
('on', True),
|
|
|
|
('off', False),
|
|
|
|
('True', True),
|
|
|
|
('False', False),
|
|
|
|
('none', False),
|
|
|
|
]
|
|
|
|
)
|
|
|
|
|
2016-04-08 14:38:05 +00:00
|
|
|
|
|
|
|
class ValidationException(Exception):
|
2022-01-04 10:53:42 +00:00
|
|
|
"""Exption from ``cls.__init__`` when configuration value is invalid."""
|
2016-04-08 14:38:05 +00:00
|
|
|
|
|
|
|
|
2020-08-12 07:42:27 +00:00
|
|
|
class Setting:
|
2016-04-08 14:38:05 +00:00
|
|
|
"""Base class of user settings"""
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def __init__(self, default_value, locked: bool = False):
|
2020-08-27 12:38:39 +00:00
|
|
|
super().__init__()
|
2016-04-08 14:38:05 +00:00
|
|
|
self.value = default_value
|
2020-10-23 14:22:55 +00:00
|
|
|
self.locked = locked
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def parse(self, data: str):
|
2020-02-23 19:52:00 +00:00
|
|
|
"""Parse ``data`` and store the result at ``self.value``
|
|
|
|
|
|
|
|
If needed, its overwritten in the inheritance.
|
|
|
|
"""
|
2016-04-08 14:38:05 +00:00
|
|
|
self.value = data
|
|
|
|
|
|
|
|
def get_value(self):
|
2020-02-23 19:52:00 +00:00
|
|
|
"""Returns the value of the setting
|
|
|
|
|
|
|
|
If needed, its overwritten in the inheritance.
|
|
|
|
"""
|
2016-04-08 14:38:05 +00:00
|
|
|
return self.value
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def save(self, name: str, resp: flask.Response):
|
2022-09-27 15:01:00 +00:00
|
|
|
"""Save cookie ``name`` in the HTTP response object
|
2020-02-23 19:52:00 +00:00
|
|
|
|
|
|
|
If needed, its overwritten in the inheritance."""
|
2016-11-30 17:43:03 +00:00
|
|
|
resp.set_cookie(name, self.value, max_age=COOKIE_MAX_AGE)
|
2016-04-08 14:38:05 +00:00
|
|
|
|
|
|
|
|
|
|
|
class StringSetting(Setting):
|
|
|
|
"""Setting of plain string values"""
|
|
|
|
|
|
|
|
|
|
|
|
class EnumStringSetting(Setting):
|
|
|
|
"""Setting of a value which can only come from the given choices"""
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def __init__(self, default_value: str, choices: Iterable[str], locked=False):
|
|
|
|
super().__init__(default_value, locked)
|
|
|
|
self.choices = choices
|
2016-11-14 21:24:40 +00:00
|
|
|
self._validate_selection(self.value)
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def _validate_selection(self, selection: str):
|
|
|
|
if selection not in self.choices:
|
2020-02-23 19:52:00 +00:00
|
|
|
raise ValidationException('Invalid value: "{0}"'.format(selection))
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def parse(self, data: str):
|
2021-12-27 08:26:22 +00:00
|
|
|
"""Parse and validate ``data`` and store the result at ``self.value``"""
|
2016-12-14 02:55:56 +00:00
|
|
|
self._validate_selection(data)
|
2016-04-08 14:38:05 +00:00
|
|
|
self.value = data
|
|
|
|
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
class MultipleChoiceSetting(Setting):
|
2016-04-08 14:38:05 +00:00
|
|
|
"""Setting of values which can only come from the given choices"""
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def __init__(self, default_value: List[str], choices: Iterable[str], locked=False):
|
|
|
|
super().__init__(default_value, locked)
|
|
|
|
self.choices = choices
|
|
|
|
self._validate_selections(self.value)
|
|
|
|
|
|
|
|
def _validate_selections(self, selections: List[str]):
|
2016-11-14 21:24:40 +00:00
|
|
|
for item in selections:
|
2022-01-04 10:53:42 +00:00
|
|
|
if item not in self.choices:
|
2016-11-14 21:24:40 +00:00
|
|
|
raise ValidationException('Invalid value: "{0}"'.format(selections))
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def parse(self, data: str):
|
2021-12-27 08:26:22 +00:00
|
|
|
"""Parse and validate ``data`` and store the result at ``self.value``"""
|
2016-04-08 14:38:05 +00:00
|
|
|
if data == '':
|
|
|
|
self.value = []
|
|
|
|
return
|
|
|
|
|
|
|
|
elements = data.split(',')
|
2016-11-14 21:24:40 +00:00
|
|
|
self._validate_selections(elements)
|
2016-04-08 14:38:05 +00:00
|
|
|
self.value = elements
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def parse_form(self, data: List[str]):
|
2020-10-23 14:22:55 +00:00
|
|
|
if self.locked:
|
|
|
|
return
|
|
|
|
|
2016-04-08 14:38:05 +00:00
|
|
|
self.value = []
|
|
|
|
for choice in data:
|
2022-01-04 10:53:42 +00:00
|
|
|
if choice in self.choices and choice not in self.value:
|
2016-04-08 14:38:05 +00:00
|
|
|
self.value.append(choice)
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def save(self, name: str, resp: flask.Response):
|
2022-09-27 15:01:00 +00:00
|
|
|
"""Save cookie ``name`` in the HTTP response object"""
|
2016-04-08 14:38:05 +00:00
|
|
|
resp.set_cookie(name, ','.join(self.value), max_age=COOKIE_MAX_AGE)
|
|
|
|
|
|
|
|
|
2020-02-01 10:01:17 +00:00
|
|
|
class SetSetting(Setting):
|
2021-12-27 08:26:22 +00:00
|
|
|
"""Setting of values of type ``set`` (comma separated string)"""
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
self.values = set()
|
2020-02-01 10:01:17 +00:00
|
|
|
|
|
|
|
def get_value(self):
|
2021-12-27 08:26:22 +00:00
|
|
|
"""Returns a string with comma separated values."""
|
2020-02-01 10:01:17 +00:00
|
|
|
return ','.join(self.values)
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def parse(self, data: str):
|
2021-12-27 08:26:22 +00:00
|
|
|
"""Parse and validate ``data`` and store the result at ``self.value``"""
|
2020-02-01 10:01:17 +00:00
|
|
|
if data == '':
|
2022-01-04 10:53:42 +00:00
|
|
|
self.values = set()
|
2020-02-01 10:01:17 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
elements = data.split(',')
|
|
|
|
for element in elements:
|
|
|
|
self.values.add(element)
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def parse_form(self, data: str):
|
2020-10-23 14:22:55 +00:00
|
|
|
if self.locked:
|
|
|
|
return
|
|
|
|
|
2020-02-01 10:01:17 +00:00
|
|
|
elements = data.split(',')
|
2022-01-04 10:53:42 +00:00
|
|
|
self.values = set(elements)
|
2020-02-01 10:01:17 +00:00
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def save(self, name: str, resp: flask.Response):
|
2022-09-27 15:01:00 +00:00
|
|
|
"""Save cookie ``name`` in the HTTP response object"""
|
2020-02-01 10:01:17 +00:00
|
|
|
resp.set_cookie(name, ','.join(self.values), max_age=COOKIE_MAX_AGE)
|
|
|
|
|
|
|
|
|
2016-12-14 02:55:56 +00:00
|
|
|
class SearchLanguageSetting(EnumStringSetting):
|
|
|
|
"""Available choices may change, so user's value may not be in choices anymore"""
|
|
|
|
|
2020-02-23 09:03:42 +00:00
|
|
|
def _validate_selection(self, selection):
|
2022-12-16 20:28:57 +00:00
|
|
|
if selection != '' and selection != 'auto' and not VALID_LANGUAGE_CODE.match(selection):
|
2020-02-23 09:03:42 +00:00
|
|
|
raise ValidationException('Invalid language code: "{0}"'.format(selection))
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def parse(self, data: str):
|
2021-12-27 08:26:22 +00:00
|
|
|
"""Parse and validate ``data`` and store the result at ``self.value``"""
|
2022-01-04 10:53:42 +00:00
|
|
|
if data not in self.choices and data != self.value:
|
2016-12-14 02:55:56 +00:00
|
|
|
# hack to give some backwards compatibility with old language cookies
|
|
|
|
data = str(data).replace('_', '-')
|
2021-07-03 15:51:39 +00:00
|
|
|
lang = data.split('-', maxsplit=1)[0]
|
2022-01-04 10:53:42 +00:00
|
|
|
|
2016-12-14 02:55:56 +00:00
|
|
|
if data in self.choices:
|
|
|
|
pass
|
|
|
|
elif lang in self.choices:
|
|
|
|
data = lang
|
|
|
|
else:
|
2016-12-14 05:51:15 +00:00
|
|
|
data = self.value
|
2020-10-01 09:29:31 +00:00
|
|
|
self._validate_selection(data)
|
2016-12-14 02:55:56 +00:00
|
|
|
self.value = data
|
|
|
|
|
|
|
|
|
2016-04-08 14:38:05 +00:00
|
|
|
class MapSetting(Setting):
|
|
|
|
"""Setting of a value that has to be translated in order to be storable"""
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def __init__(self, default_value, map: Dict[str, object], locked=False): # pylint: disable=redefined-builtin
|
|
|
|
super().__init__(default_value, locked)
|
|
|
|
self.map = map
|
|
|
|
|
|
|
|
if self.value not in self.map.values():
|
2016-04-08 14:38:05 +00:00
|
|
|
raise ValidationException('Invalid default value')
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def parse(self, data: str):
|
2021-12-27 08:26:22 +00:00
|
|
|
"""Parse and validate ``data`` and store the result at ``self.value``"""
|
2022-01-04 10:53:42 +00:00
|
|
|
|
2016-04-08 14:38:05 +00:00
|
|
|
if data not in self.map:
|
|
|
|
raise ValidationException('Invalid choice: {0}'.format(data))
|
|
|
|
self.value = self.map[data]
|
2020-02-23 19:52:00 +00:00
|
|
|
self.key = data # pylint: disable=attribute-defined-outside-init
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def save(self, name: str, resp: flask.Response):
|
2022-09-27 15:01:00 +00:00
|
|
|
"""Save cookie ``name`` in the HTTP response object"""
|
2017-01-21 19:08:08 +00:00
|
|
|
if hasattr(self, 'key'):
|
2016-11-30 17:43:03 +00:00
|
|
|
resp.set_cookie(name, self.key, max_age=COOKIE_MAX_AGE)
|
2016-04-08 14:38:05 +00:00
|
|
|
|
|
|
|
|
2023-08-22 13:35:46 +00:00
|
|
|
class BooleanSetting(Setting):
|
|
|
|
"""Setting of a boolean value that has to be translated in order to be storable"""
|
|
|
|
|
|
|
|
def normalized_str(self, val):
|
|
|
|
for v_str, v_obj in MAP_STR2BOOL.items():
|
|
|
|
if val == v_obj:
|
|
|
|
return v_str
|
|
|
|
raise ValueError("Invalid value: %s (%s) is not a boolean!" % (repr(val), type(val)))
|
|
|
|
|
|
|
|
def parse(self, data: str):
|
|
|
|
"""Parse and validate ``data`` and store the result at ``self.value``"""
|
|
|
|
self.value = MAP_STR2BOOL[data]
|
|
|
|
self.key = self.normalized_str(self.value) # pylint: disable=attribute-defined-outside-init
|
|
|
|
|
|
|
|
def save(self, name: str, resp: flask.Response):
|
|
|
|
"""Save cookie ``name`` in the HTTP response object"""
|
|
|
|
if hasattr(self, 'key'):
|
|
|
|
resp.set_cookie(name, self.key, max_age=COOKIE_MAX_AGE)
|
|
|
|
|
|
|
|
|
2022-01-06 17:45:50 +00:00
|
|
|
class BooleanChoices:
|
|
|
|
"""Maps strings to booleans that are either true or false."""
|
2022-01-04 10:53:42 +00:00
|
|
|
|
2022-01-06 17:45:50 +00:00
|
|
|
def __init__(self, name: str, choices: Dict[str, bool], locked: bool = False):
|
2022-01-04 13:57:39 +00:00
|
|
|
self.name = name
|
2022-01-04 10:53:42 +00:00
|
|
|
self.choices = choices
|
2022-01-06 17:45:50 +00:00
|
|
|
self.locked = locked
|
2022-01-13 18:39:18 +00:00
|
|
|
self.default_choices = dict(choices)
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2021-09-07 11:34:35 +00:00
|
|
|
def transform_form_items(self, items):
|
2016-04-08 14:38:05 +00:00
|
|
|
return items
|
|
|
|
|
2021-09-07 11:34:35 +00:00
|
|
|
def transform_values(self, values):
|
2016-04-08 14:38:05 +00:00
|
|
|
return values
|
|
|
|
|
2022-01-04 13:14:37 +00:00
|
|
|
def parse_cookie(self, data_disabled: str, data_enabled: str):
|
2022-01-06 17:45:50 +00:00
|
|
|
for disabled in data_disabled.split(','):
|
|
|
|
if disabled in self.choices:
|
|
|
|
self.choices[disabled] = False
|
|
|
|
|
|
|
|
for enabled in data_enabled.split(','):
|
|
|
|
if enabled in self.choices:
|
|
|
|
self.choices[enabled] = True
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def parse_form(self, items: List[str]):
|
2020-10-23 14:22:55 +00:00
|
|
|
if self.locked:
|
|
|
|
return
|
|
|
|
|
2022-01-06 17:45:50 +00:00
|
|
|
disabled = self.transform_form_items(items)
|
|
|
|
for setting in self.choices:
|
2022-01-15 18:54:09 +00:00
|
|
|
if setting in disabled:
|
|
|
|
self.choices[setting] = False
|
2022-01-06 17:45:50 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def enabled(self):
|
|
|
|
return (k for k, v in self.choices.items() if v)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def disabled(self):
|
|
|
|
return (k for k, v in self.choices.items() if not v)
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2022-01-04 13:57:39 +00:00
|
|
|
def save(self, resp: flask.Response):
|
2022-09-27 15:01:00 +00:00
|
|
|
"""Save cookie in the HTTP response object"""
|
2022-01-13 18:39:18 +00:00
|
|
|
disabled_changed = (k for k in self.disabled if self.default_choices[k])
|
|
|
|
enabled_changed = (k for k in self.enabled if not self.default_choices[k])
|
|
|
|
resp.set_cookie('disabled_{0}'.format(self.name), ','.join(disabled_changed), max_age=COOKIE_MAX_AGE)
|
|
|
|
resp.set_cookie('enabled_{0}'.format(self.name), ','.join(enabled_changed), max_age=COOKIE_MAX_AGE)
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2021-09-07 11:34:35 +00:00
|
|
|
def get_disabled(self):
|
2022-01-06 17:45:50 +00:00
|
|
|
return self.transform_values(list(self.disabled))
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2021-09-07 11:34:35 +00:00
|
|
|
def get_enabled(self):
|
2022-01-06 17:45:50 +00:00
|
|
|
return self.transform_values(list(self.enabled))
|
2016-04-08 14:38:05 +00:00
|
|
|
|
|
|
|
|
2022-01-06 17:45:50 +00:00
|
|
|
class EnginesSetting(BooleanChoices):
|
2020-02-23 19:52:00 +00:00
|
|
|
"""Engine settings"""
|
2016-07-10 14:44:27 +00:00
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def __init__(self, default_value, engines: Iterable[Engine]):
|
2022-01-06 17:45:50 +00:00
|
|
|
choices = {}
|
2022-01-04 10:53:42 +00:00
|
|
|
for engine in engines:
|
2016-04-08 14:38:05 +00:00
|
|
|
for category in engine.categories:
|
2022-07-24 07:32:05 +00:00
|
|
|
if not category in list(settings['categories_as_tabs'].keys()) + [DEFAULT_CATEGORY]:
|
2022-01-04 14:39:19 +00:00
|
|
|
continue
|
2022-01-06 17:45:50 +00:00
|
|
|
choices['{}__{}'.format(engine.name, category)] = not engine.disabled
|
|
|
|
super().__init__(default_value, choices)
|
2016-04-08 14:38:05 +00:00
|
|
|
|
|
|
|
def transform_form_items(self, items):
|
2021-12-27 08:26:22 +00:00
|
|
|
return [item[len('engine_') :].replace('_', ' ').replace(' ', '__') for item in items]
|
2016-04-08 14:38:05 +00:00
|
|
|
|
|
|
|
def transform_values(self, values):
|
2016-05-04 14:14:04 +00:00
|
|
|
if len(values) == 1 and next(iter(values)) == '':
|
2021-08-31 08:40:29 +00:00
|
|
|
return []
|
2016-04-08 14:38:05 +00:00
|
|
|
transformed_values = []
|
|
|
|
for value in values:
|
|
|
|
engine, category = value.split('__')
|
|
|
|
transformed_values.append((engine, category))
|
|
|
|
return transformed_values
|
|
|
|
|
|
|
|
|
2022-01-06 17:45:50 +00:00
|
|
|
class PluginsSetting(BooleanChoices):
|
2020-02-23 19:52:00 +00:00
|
|
|
"""Plugin settings"""
|
2016-07-10 14:44:27 +00:00
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def __init__(self, default_value, plugins: Iterable[Plugin]):
|
2022-01-06 17:45:50 +00:00
|
|
|
super().__init__(default_value, {plugin.id: plugin.default_on for plugin in plugins})
|
2016-04-08 14:38:05 +00:00
|
|
|
|
|
|
|
def transform_form_items(self, items):
|
2021-12-27 08:26:22 +00:00
|
|
|
return [item[len('plugin_') :] for item in items]
|
2016-04-08 14:38:05 +00:00
|
|
|
|
|
|
|
|
2023-01-30 17:40:22 +00:00
|
|
|
class ClientPref:
|
|
|
|
"""Container to assemble client prefferences and settings."""
|
|
|
|
|
|
|
|
# hint: searx.webapp.get_client_settings should be moved into this class
|
|
|
|
|
|
|
|
locale: babel.Locale
|
|
|
|
"""Locale prefered by the client."""
|
|
|
|
|
|
|
|
def __init__(self, locale: Optional[babel.Locale] = None):
|
|
|
|
self.locale = locale
|
|
|
|
|
|
|
|
@property
|
|
|
|
def locale_tag(self):
|
|
|
|
if self.locale is None:
|
|
|
|
return None
|
|
|
|
tag = self.locale.language
|
|
|
|
if self.locale.territory:
|
|
|
|
tag += '-' + self.locale.territory
|
|
|
|
return tag
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_http_request(cls, http_request: flask.Request):
|
|
|
|
"""Build ClientPref object from HTTP request.
|
|
|
|
|
|
|
|
- `Accept-Language used for locale setting
|
|
|
|
<https://www.w3.org/International/questions/qa-accept-lang-locales.en>`__
|
|
|
|
|
|
|
|
"""
|
|
|
|
al_header = http_request.headers.get("Accept-Language")
|
|
|
|
if not al_header:
|
|
|
|
return cls(locale=None)
|
|
|
|
|
|
|
|
pairs = []
|
|
|
|
for l in al_header.split(','):
|
|
|
|
# fmt: off
|
|
|
|
lang, qvalue = [_.strip() for _ in (l.split(';') + ['q=1',])[:2]]
|
|
|
|
# fmt: on
|
|
|
|
try:
|
|
|
|
qvalue = float(qvalue.split('=')[-1])
|
|
|
|
locale = babel.Locale.parse(lang, sep='-')
|
|
|
|
except (ValueError, babel.core.UnknownLocaleError):
|
|
|
|
continue
|
|
|
|
pairs.append((locale, qvalue))
|
2023-05-22 10:17:57 +00:00
|
|
|
|
|
|
|
locale = None
|
|
|
|
if pairs:
|
|
|
|
pairs.sort(reverse=True, key=lambda x: x[1])
|
|
|
|
locale = pairs[0][0]
|
|
|
|
return cls(locale=locale)
|
2023-01-30 17:40:22 +00:00
|
|
|
|
|
|
|
|
2020-08-12 07:42:27 +00:00
|
|
|
class Preferences:
|
2017-07-10 10:47:25 +00:00
|
|
|
"""Validates and saves preferences to cookies"""
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2023-01-30 17:40:22 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
themes: List[str],
|
|
|
|
categories: List[str],
|
|
|
|
engines: Dict[str, Engine],
|
|
|
|
plugins: Iterable[Plugin],
|
|
|
|
client: Optional[ClientPref] = None,
|
|
|
|
):
|
|
|
|
|
2020-08-27 12:38:39 +00:00
|
|
|
super().__init__()
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
self.key_value_settings: Dict[str, Setting] = {
|
2021-12-27 08:16:03 +00:00
|
|
|
# fmt: off
|
2020-02-23 19:52:00 +00:00
|
|
|
'categories': MultipleChoiceSetting(
|
2020-10-23 14:22:55 +00:00
|
|
|
['general'],
|
2022-01-04 10:53:42 +00:00
|
|
|
locked=is_locked('categories'),
|
2020-10-23 14:22:55 +00:00
|
|
|
choices=categories + ['none']
|
2020-02-23 19:52:00 +00:00
|
|
|
),
|
|
|
|
'language': SearchLanguageSetting(
|
2021-05-28 16:45:22 +00:00
|
|
|
settings['search']['default_lang'],
|
2022-01-04 10:53:42 +00:00
|
|
|
locked=is_locked('language'),
|
2021-10-21 08:41:57 +00:00
|
|
|
choices=settings['search']['languages'] + ['']
|
2020-02-23 19:52:00 +00:00
|
|
|
),
|
|
|
|
'locale': EnumStringSetting(
|
2021-05-28 16:45:22 +00:00
|
|
|
settings['ui']['default_locale'],
|
2022-01-04 10:53:42 +00:00
|
|
|
locked=is_locked('locale'),
|
2021-08-03 13:13:00 +00:00
|
|
|
choices=list(LOCALE_NAMES.keys()) + ['']
|
2020-02-23 19:52:00 +00:00
|
|
|
),
|
|
|
|
'autocomplete': EnumStringSetting(
|
2021-05-28 16:45:22 +00:00
|
|
|
settings['search']['autocomplete'],
|
2022-01-04 10:53:42 +00:00
|
|
|
locked=is_locked('autocomplete'),
|
2020-02-23 19:52:00 +00:00
|
|
|
choices=list(autocomplete.backends.keys()) + ['']
|
|
|
|
),
|
2024-08-11 08:39:46 +00:00
|
|
|
'favicon_resolver': EnumStringSetting(
|
|
|
|
settings['search']['favicon_resolver'],
|
|
|
|
locked=is_locked('favicon_resolver'),
|
2024-08-19 15:47:54 +00:00
|
|
|
choices=list(favicons.proxy.CFG.resolver_map.keys()) + ['']
|
2024-08-11 08:39:46 +00:00
|
|
|
),
|
2023-08-22 13:35:46 +00:00
|
|
|
'image_proxy': BooleanSetting(
|
2021-05-28 16:45:22 +00:00
|
|
|
settings['server']['image_proxy'],
|
2023-08-22 13:35:46 +00:00
|
|
|
locked=is_locked('image_proxy')
|
2020-02-23 19:52:00 +00:00
|
|
|
),
|
|
|
|
'method': EnumStringSetting(
|
2021-05-28 16:45:22 +00:00
|
|
|
settings['server']['method'],
|
2022-01-04 10:53:42 +00:00
|
|
|
locked=is_locked('method'),
|
2020-02-23 19:52:00 +00:00
|
|
|
choices=('GET', 'POST')
|
|
|
|
),
|
|
|
|
'safesearch': MapSetting(
|
2021-05-28 16:45:22 +00:00
|
|
|
settings['search']['safe_search'],
|
2022-01-04 10:53:42 +00:00
|
|
|
locked=is_locked('safesearch'),
|
2020-02-23 19:56:05 +00:00
|
|
|
map={
|
|
|
|
'0': 0,
|
|
|
|
'1': 1,
|
|
|
|
'2': 2
|
|
|
|
}
|
|
|
|
),
|
2020-02-23 19:52:00 +00:00
|
|
|
'theme': EnumStringSetting(
|
2021-05-28 16:45:22 +00:00
|
|
|
settings['ui']['default_theme'],
|
2022-01-04 10:53:42 +00:00
|
|
|
locked=is_locked('theme'),
|
2020-02-23 19:52:00 +00:00
|
|
|
choices=themes
|
|
|
|
),
|
2023-08-22 13:35:46 +00:00
|
|
|
'results_on_new_tab': BooleanSetting(
|
2021-05-28 16:45:22 +00:00
|
|
|
settings['ui']['results_on_new_tab'],
|
2023-08-22 13:35:46 +00:00
|
|
|
locked=is_locked('results_on_new_tab')
|
2020-02-23 19:52:00 +00:00
|
|
|
),
|
|
|
|
'doi_resolver': MultipleChoiceSetting(
|
2021-04-04 11:36:33 +00:00
|
|
|
[settings['default_doi_resolver'], ],
|
2022-01-04 10:53:42 +00:00
|
|
|
locked=is_locked('doi_resolver'),
|
2020-10-23 14:22:55 +00:00
|
|
|
choices=DOI_RESOLVERS
|
2020-02-23 19:52:00 +00:00
|
|
|
),
|
2021-11-19 12:49:16 +00:00
|
|
|
'simple_style': EnumStringSetting(
|
|
|
|
settings['ui']['theme_args']['simple_style'],
|
2022-01-04 10:53:42 +00:00
|
|
|
locked=is_locked('simple_style'),
|
2024-09-20 14:44:53 +00:00
|
|
|
choices=['', 'auto', 'light', 'dark', 'black']
|
2021-11-19 12:49:16 +00:00
|
|
|
),
|
2023-08-22 13:35:46 +00:00
|
|
|
'center_alignment': BooleanSetting(
|
2022-07-03 15:35:54 +00:00
|
|
|
settings['ui']['center_alignment'],
|
2023-08-22 13:35:46 +00:00
|
|
|
locked=is_locked('center_alignment')
|
2022-06-03 12:10:48 +00:00
|
|
|
),
|
2023-08-22 13:35:46 +00:00
|
|
|
'advanced_search': BooleanSetting(
|
2021-05-28 16:45:22 +00:00
|
|
|
settings['ui']['advanced_search'],
|
2023-08-22 13:35:46 +00:00
|
|
|
locked=is_locked('advanced_search')
|
2020-11-22 17:00:21 +00:00
|
|
|
),
|
2023-08-22 13:35:46 +00:00
|
|
|
'query_in_title': BooleanSetting(
|
2021-11-06 11:26:48 +00:00
|
|
|
settings['ui']['query_in_title'],
|
2023-08-22 13:35:46 +00:00
|
|
|
locked=is_locked('query_in_title')
|
2021-11-06 11:26:48 +00:00
|
|
|
),
|
2023-08-22 13:35:46 +00:00
|
|
|
'infinite_scroll': BooleanSetting(
|
2022-01-23 10:37:57 +00:00
|
|
|
settings['ui']['infinite_scroll'],
|
2023-08-22 13:35:46 +00:00
|
|
|
locked=is_locked('infinite_scroll')
|
2022-01-23 10:37:57 +00:00
|
|
|
),
|
2023-09-09 14:49:14 +00:00
|
|
|
'search_on_category_select': BooleanSetting(
|
|
|
|
settings['ui']['search_on_category_select'],
|
|
|
|
locked=is_locked('search_on_category_select')
|
|
|
|
),
|
2023-09-16 15:14:18 +00:00
|
|
|
'hotkeys': EnumStringSetting(
|
2023-10-07 19:05:46 +00:00
|
|
|
settings['ui']['hotkeys'],
|
2023-09-16 15:14:18 +00:00
|
|
|
choices=['default', 'vim']
|
|
|
|
),
|
2021-12-27 08:16:03 +00:00
|
|
|
# fmt: on
|
2020-02-23 19:52:00 +00:00
|
|
|
}
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
self.engines = EnginesSetting('engines', engines=engines.values())
|
|
|
|
self.plugins = PluginsSetting('plugins', plugins=plugins)
|
2020-02-01 10:01:17 +00:00
|
|
|
self.tokens = SetSetting('tokens')
|
2023-01-30 17:40:22 +00:00
|
|
|
self.client = client or ClientPref()
|
2022-01-04 10:53:42 +00:00
|
|
|
self.unknown_params: Dict[str, str] = {}
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2017-07-10 10:47:25 +00:00
|
|
|
def get_as_url_params(self):
|
2020-02-23 19:52:00 +00:00
|
|
|
"""Return preferences as URL parameters"""
|
2017-07-10 10:47:25 +00:00
|
|
|
settings_kv = {}
|
|
|
|
for k, v in self.key_value_settings.items():
|
2020-10-23 14:22:55 +00:00
|
|
|
if v.locked:
|
|
|
|
continue
|
2017-07-10 10:47:25 +00:00
|
|
|
if isinstance(v, MultipleChoiceSetting):
|
|
|
|
settings_kv[k] = ','.join(v.get_value())
|
|
|
|
else:
|
|
|
|
settings_kv[k] = v.get_value()
|
|
|
|
|
|
|
|
settings_kv['disabled_engines'] = ','.join(self.engines.disabled)
|
|
|
|
settings_kv['enabled_engines'] = ','.join(self.engines.enabled)
|
|
|
|
|
|
|
|
settings_kv['disabled_plugins'] = ','.join(self.plugins.disabled)
|
|
|
|
settings_kv['enabled_plugins'] = ','.join(self.plugins.enabled)
|
|
|
|
|
2020-02-01 10:01:17 +00:00
|
|
|
settings_kv['tokens'] = ','.join(self.tokens.values)
|
|
|
|
|
2020-08-06 15:42:46 +00:00
|
|
|
return urlsafe_b64encode(compress(urlencode(settings_kv).encode())).decode()
|
2017-10-25 21:56:37 +00:00
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def parse_encoded_data(self, input_data: str):
|
2020-02-23 19:52:00 +00:00
|
|
|
"""parse (base64) preferences from request (``flask.request.form['preferences']``)"""
|
2021-06-26 15:14:13 +00:00
|
|
|
bin_data = decompress(urlsafe_b64decode(input_data))
|
2019-07-17 07:42:40 +00:00
|
|
|
dict_data = {}
|
2022-11-24 19:12:06 +00:00
|
|
|
for x, y in parse_qs(bin_data.decode('ascii'), keep_blank_values=True).items():
|
2021-06-26 15:14:13 +00:00
|
|
|
dict_data[x] = y[0]
|
2019-07-17 07:42:40 +00:00
|
|
|
self.parse_dict(dict_data)
|
2017-07-10 10:47:25 +00:00
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def parse_dict(self, input_data: Dict[str, str]):
|
2020-02-23 19:52:00 +00:00
|
|
|
"""parse preferences from request (``flask.request.form``)"""
|
2016-11-30 17:43:03 +00:00
|
|
|
for user_setting_name, user_setting in input_data.items():
|
2016-04-08 14:38:05 +00:00
|
|
|
if user_setting_name in self.key_value_settings:
|
2020-10-23 14:22:55 +00:00
|
|
|
if self.key_value_settings[user_setting_name].locked:
|
|
|
|
continue
|
2016-04-08 14:38:05 +00:00
|
|
|
self.key_value_settings[user_setting_name].parse(user_setting)
|
|
|
|
elif user_setting_name == 'disabled_engines':
|
2022-01-04 13:14:37 +00:00
|
|
|
self.engines.parse_cookie(input_data.get('disabled_engines', ''), input_data.get('enabled_engines', ''))
|
2016-04-08 14:38:05 +00:00
|
|
|
elif user_setting_name == 'disabled_plugins':
|
2022-01-04 13:14:37 +00:00
|
|
|
self.plugins.parse_cookie(input_data.get('disabled_plugins', ''), input_data.get('enabled_plugins', ''))
|
2020-02-01 10:01:17 +00:00
|
|
|
elif user_setting_name == 'tokens':
|
|
|
|
self.tokens.parse(user_setting)
|
2021-12-27 08:26:22 +00:00
|
|
|
elif not any(
|
|
|
|
user_setting_name.startswith(x) for x in ['enabled_', 'disabled_', 'engine_', 'category_', 'plugin_']
|
|
|
|
):
|
2017-12-05 21:30:20 +00:00
|
|
|
self.unknown_params[user_setting_name] = user_setting
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def parse_form(self, input_data: Dict[str, str]):
|
2020-02-23 19:52:00 +00:00
|
|
|
"""Parse formular (``<input>``) data from a ``flask.request.form``"""
|
2016-04-08 14:38:05 +00:00
|
|
|
disabled_engines = []
|
|
|
|
enabled_categories = []
|
|
|
|
disabled_plugins = []
|
2023-08-22 13:35:46 +00:00
|
|
|
|
|
|
|
# boolean preferences are not sent by the form if they're false,
|
|
|
|
# so we have to add them as false manually if they're not sent (then they would be true)
|
|
|
|
for key, setting in self.key_value_settings.items():
|
|
|
|
if key not in input_data.keys() and isinstance(setting, BooleanSetting):
|
|
|
|
input_data[key] = 'False'
|
|
|
|
|
2016-11-30 17:43:03 +00:00
|
|
|
for user_setting_name, user_setting in input_data.items():
|
2016-04-08 14:38:05 +00:00
|
|
|
if user_setting_name in self.key_value_settings:
|
|
|
|
self.key_value_settings[user_setting_name].parse(user_setting)
|
|
|
|
elif user_setting_name.startswith('engine_'):
|
|
|
|
disabled_engines.append(user_setting_name)
|
|
|
|
elif user_setting_name.startswith('category_'):
|
2021-12-27 08:26:22 +00:00
|
|
|
enabled_categories.append(user_setting_name[len('category_') :])
|
2016-04-08 14:38:05 +00:00
|
|
|
elif user_setting_name.startswith('plugin_'):
|
|
|
|
disabled_plugins.append(user_setting_name)
|
2020-02-01 10:01:17 +00:00
|
|
|
elif user_setting_name == 'tokens':
|
|
|
|
self.tokens.parse_form(user_setting)
|
2016-06-25 23:44:42 +00:00
|
|
|
else:
|
|
|
|
self.unknown_params[user_setting_name] = user_setting
|
2016-04-08 14:38:05 +00:00
|
|
|
self.key_value_settings['categories'].parse_form(enabled_categories)
|
|
|
|
self.engines.parse_form(disabled_engines)
|
|
|
|
self.plugins.parse_form(disabled_plugins)
|
|
|
|
|
|
|
|
# cannot be used in case of engines or plugins
|
2022-01-04 10:53:42 +00:00
|
|
|
def get_value(self, user_setting_name: str):
|
2021-12-27 08:26:22 +00:00
|
|
|
"""Returns the value for ``user_setting_name``"""
|
2020-02-23 19:52:00 +00:00
|
|
|
ret_val = None
|
2016-04-08 14:38:05 +00:00
|
|
|
if user_setting_name in self.key_value_settings:
|
2020-02-23 19:52:00 +00:00
|
|
|
ret_val = self.key_value_settings[user_setting_name].get_value()
|
2017-12-05 21:30:20 +00:00
|
|
|
if user_setting_name in self.unknown_params:
|
2020-02-23 19:52:00 +00:00
|
|
|
ret_val = self.unknown_params[user_setting_name]
|
|
|
|
return ret_val
|
2016-04-08 14:38:05 +00:00
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def save(self, resp: flask.Response):
|
2022-09-27 15:01:00 +00:00
|
|
|
"""Save cookie in the HTTP response object"""
|
2016-11-30 17:43:03 +00:00
|
|
|
for user_setting_name, user_setting in self.key_value_settings.items():
|
2021-07-03 15:51:39 +00:00
|
|
|
# pylint: disable=unnecessary-dict-index-lookup
|
2020-10-23 14:22:55 +00:00
|
|
|
if self.key_value_settings[user_setting_name].locked:
|
|
|
|
continue
|
2016-04-08 14:38:05 +00:00
|
|
|
user_setting.save(user_setting_name, resp)
|
|
|
|
self.engines.save(resp)
|
|
|
|
self.plugins.save(resp)
|
2020-02-01 10:01:17 +00:00
|
|
|
self.tokens.save('tokens', resp)
|
2016-06-25 23:44:42 +00:00
|
|
|
for k, v in self.unknown_params.items():
|
|
|
|
resp.set_cookie(k, v, max_age=COOKIE_MAX_AGE)
|
2016-04-08 14:38:05 +00:00
|
|
|
return resp
|
2020-02-01 10:01:17 +00:00
|
|
|
|
2021-09-07 11:34:35 +00:00
|
|
|
def validate_token(self, engine):
|
2020-02-01 10:01:17 +00:00
|
|
|
valid = True
|
|
|
|
if hasattr(engine, 'tokens') and engine.tokens:
|
|
|
|
valid = False
|
|
|
|
for token in self.tokens.values:
|
|
|
|
if token in engine.tokens:
|
|
|
|
valid = True
|
|
|
|
break
|
|
|
|
|
|
|
|
return valid
|
2020-10-23 14:22:55 +00:00
|
|
|
|
|
|
|
|
2022-01-04 10:53:42 +00:00
|
|
|
def is_locked(setting_name: str):
|
2021-12-27 08:26:22 +00:00
|
|
|
"""Checks if a given setting name is locked by settings.yml"""
|
2020-10-23 14:22:55 +00:00
|
|
|
if 'preferences' not in settings:
|
|
|
|
return False
|
|
|
|
if 'lock' not in settings['preferences']:
|
|
|
|
return False
|
|
|
|
return setting_name in settings['preferences']['lock']
|