2020-12-16 13:41:32 +01:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
2023-09-15 09:53:03 +02:00
|
|
|
"""Processors for engine-type: ``online_currency``
|
2021-04-27 15:13:39 +02:00
|
|
|
|
|
|
|
"""
|
2020-12-16 13:41:32 +01:00
|
|
|
|
|
|
|
import unicodedata
|
|
|
|
import re
|
|
|
|
|
|
|
|
from searx.data import CURRENCIES
|
|
|
|
from .online import OnlineProcessor
|
|
|
|
|
|
|
|
parser_re = re.compile('.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I)
|
|
|
|
|
2021-12-27 09:26:22 +01:00
|
|
|
|
2020-12-16 13:41:32 +01:00
|
|
|
def normalize_name(name):
|
|
|
|
name = name.lower().replace('-', ' ').rstrip('s')
|
|
|
|
name = re.sub(' +', ' ', name)
|
|
|
|
return unicodedata.normalize('NFKD', name).lower()
|
|
|
|
|
2021-12-27 09:26:22 +01:00
|
|
|
|
2020-12-16 13:41:32 +01:00
|
|
|
def name_to_iso4217(name):
|
|
|
|
name = normalize_name(name)
|
|
|
|
currency = CURRENCIES['names'].get(name, [name])
|
2021-02-19 12:52:26 +01:00
|
|
|
if isinstance(currency, str):
|
|
|
|
return currency
|
2020-12-16 13:41:32 +01:00
|
|
|
return currency[0]
|
|
|
|
|
2021-12-27 09:26:22 +01:00
|
|
|
|
2020-12-16 13:41:32 +01:00
|
|
|
def iso4217_to_name(iso4217, language):
|
|
|
|
return CURRENCIES['iso4217'].get(iso4217, {}).get(language, iso4217)
|
|
|
|
|
2021-12-27 09:26:22 +01:00
|
|
|
|
2020-12-16 13:41:32 +01:00
|
|
|
class OnlineCurrencyProcessor(OnlineProcessor):
|
2021-04-27 15:13:39 +02:00
|
|
|
"""Processor class used by ``online_currency`` engines."""
|
|
|
|
|
2020-12-16 13:41:32 +01:00
|
|
|
engine_type = 'online_currency'
|
|
|
|
|
|
|
|
def get_params(self, search_query, engine_category):
|
2022-09-29 20:54:46 +02:00
|
|
|
"""Returns a set of :ref:`request params <engine request online_currency>`
|
|
|
|
or ``None`` if search query does not match to :py:obj:`parser_re`."""
|
2022-08-01 16:42:33 +02:00
|
|
|
|
2020-12-16 13:41:32 +01:00
|
|
|
params = super().get_params(search_query, engine_category)
|
|
|
|
if params is None:
|
|
|
|
return None
|
|
|
|
|
|
|
|
m = parser_re.match(search_query.query)
|
|
|
|
if not m:
|
|
|
|
return None
|
|
|
|
|
|
|
|
amount_str, from_currency, to_currency = m.groups()
|
|
|
|
try:
|
|
|
|
amount = float(amount_str)
|
|
|
|
except ValueError:
|
|
|
|
return None
|
|
|
|
from_currency = name_to_iso4217(from_currency.strip())
|
|
|
|
to_currency = name_to_iso4217(to_currency.strip())
|
|
|
|
|
|
|
|
params['amount'] = amount
|
|
|
|
params['from'] = from_currency
|
|
|
|
params['to'] = to_currency
|
|
|
|
params['from_name'] = iso4217_to_name(from_currency, 'en')
|
|
|
|
params['to_name'] = iso4217_to_name(to_currency, 'en')
|
|
|
|
return params
|
2020-12-24 09:28:16 +01:00
|
|
|
|
|
|
|
def get_default_tests(self):
|
|
|
|
tests = {}
|
|
|
|
|
|
|
|
tests['currency'] = {
|
|
|
|
'matrix': {'query': '1337 usd in rmb'},
|
|
|
|
'result_container': ['has_answer'],
|
|
|
|
}
|
|
|
|
|
|
|
|
return tests
|