From 93233c786a1970b11a2f42e5afb3e3a2d8814505 Mon Sep 17 00:00:00 2001 From: marc Date: Tue, 13 Dec 2016 20:55:56 -0600 Subject: [PATCH] Refactor search language preference. --- searx/preferences.py | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/searx/preferences.py b/searx/preferences.py index b27cfb7f4..7dc0e3172 100644 --- a/searx/preferences.py +++ b/searx/preferences.py @@ -59,18 +59,7 @@ class EnumStringSetting(Setting): self._validate_selection(self.value) def parse(self, data): - if data not in self.choices and data != self.value: - # hack to give some backwards compatibility with old language cookies - data = str(data).replace('_', '-') - lang = data[:2] - if data in self.choices: - pass - elif lang in self.choices: - data = lang - elif data == 'ar-XA': - data = 'ar-SA' - else: - data = 'all' + self._validate_selection(data) self.value = data @@ -106,6 +95,25 @@ class MultipleChoiceSetting(EnumStringSetting): resp.set_cookie(name, ','.join(self.value), max_age=COOKIE_MAX_AGE) +class SearchLanguageSetting(EnumStringSetting): + """Available choices may change, so user's value may not be in choices anymore""" + + def parse(self, data): + if data not in self.choices and data != self.value: + # hack to give some backwards compatibility with old language cookies + data = str(data).replace('_', '-') + lang = data.split('-')[0] + if data in self.choices: + pass + elif lang in self.choices: + data = lang + elif data == 'ar-XA': + data = 'ar-SA' + else: + data = 'all' + self.value = data + + class MapSetting(Setting): """Setting of a value that has to be translated in order to be storable""" @@ -227,8 +235,8 @@ class Preferences(object): super(Preferences, self).__init__() self.key_value_settings = {'categories': MultipleChoiceSetting(['general'], choices=categories), - 'language': EnumStringSetting(settings['search']['language'], - choices=LANGUAGE_CODES), + 'language': SearchLanguageSetting(settings['search']['language'], + choices=LANGUAGE_CODES), 'locale': EnumStringSetting(settings['ui']['default_locale'], choices=settings['locales'].keys() + ['']), 'autocomplete': EnumStringSetting(settings['search']['autocomplete'],