web search done right
currency conversion in calculator
Mikkel Denkercb49f611fd07
diff --git a/core/src/searcher/api.rs b/core/src/searcher/api.rsindex c09501cd..b16afa4e 100644--- a/core/src/searcher/api.rs+++ b/core/src/searcher/api.rs@@ -32,7 +32,7 @@ use crate::search_prettifier::{create_stackoverflow_sidebar, DisplayedAnswer, DisplayedEntity, DisplayedSidebar,DisplayedWebpage, HighlightedSpellCorrection,};-use crate::widgets::Widget;+use crate::widgets::{Widget, Widgets};use crate::{bangs::Bangs,collector::BucketCollector,@@ -58,6 +58,7 @@ pub struct ApiSearcher {bangs: Bangs,collector_config: CollectorConfig,thresholds: ApiThresholds,+ widgets: Widgets,}impl ApiSearcher {@@ -78,6 +79,7 @@ impl ApiSearcher {bangs,collector_config,thresholds,+ widgets: Widgets::new(),}}@@ -401,7 +403,7 @@ impl ApiSearcher {return None;}- Widget::try_new(&query.query)+ self.widgets.widget(query.query.as_str())}fn answer(&self, query: &str, webpages: &mut Vec<DisplayedWebpage>) -> Option<DisplayedAnswer> {diff --git a/core/src/widgets/calculator.rs b/core/src/widgets/calculator.rsindex e21f261e..d1b4890d 100644--- a/core/src/widgets/calculator.rs+++ b/core/src/widgets/calculator.rs@@ -14,10 +14,15 @@// You should have received a copy of the GNU Affero General Public License// along with this program. If not, see <https://www.gnu.org/licenses/>.-use crate::widgets::{Error, Result};+use crate::widgets::Error;+use anyhow::{anyhow, Result};+use hashbrown::HashMap;use rand::Rng;use serde::{Deserialize, Serialize};-use std::fmt::Debug;+use std::{+ fmt::Debug,+ sync::{Arc, Mutex},+};use utoipa::ToSchema;static DICE_REGEX: once_cell::sync::Lazy<regex::Regex> =@@ -30,30 +35,136 @@ pub struct Calculation {pub result: String,}-pub fn try_calculate(expr: &str) -> Result<Calculation> {- // if expr starts with "d[0-9]+", wrap it in "roll(...)"- let expr = if DICE_REGEX.is_match(expr) {- format!("roll({})", expr)- } else {- expr.to_string()- };+async fn get_rates() -> Result<CurrencyExchange> {+ let client = reqwest::Client::new();+ let xml = client+ .get("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml")+ .send()+ .await?+ .text()+ .await?;- let mut context = fend_core::Context::new();- context.set_random_u32_fn(|| {- let mut rng = rand::thread_rng();- rng.gen()- });+ let mut rates = HashMap::new();+ let mut buf = Vec::new();+ let mut reader = quick_xml::Reader::from_str(&xml);- let res = fend_core::evaluate(&expr, &mut context).map_err(|_| Error::CalculatorParse)?;+ // read all `Cube` nodes that has the `currency` attribute+ // and insert them into the `rates` map+ while let Ok(event) = reader.read_event(&mut buf) {+ match event {+ quick_xml::events::Event::Empty(ref e) if e.name() == b"Cube" => {+ if let Some(currency) = e+ .attributes()+ .find(|a| a.as_ref().unwrap().key == b"currency")+ .map(|a| a.unwrap().value.to_vec())+ {+ let rate = e+ .attributes()+ .find(|a| a.as_ref().unwrap().key == b"rate")+ .map(|a| a.unwrap().value.to_vec())+ .unwrap();+ rates.insert(+ String::from_utf8(currency)?,+ String::from_utf8(rate)?.parse::<f64>()?,+ );+ }+ }+ quick_xml::events::Event::Eof => break,+ _ => (),+ }+ }++ rates.insert("EUR".to_string(), 1.0);++ Ok(CurrencyExchange { rates })+}++#[derive(Debug, Default)]+struct CurrencyExchange {+ rates: HashMap<String, f64>,+}++impl CurrencyExchange {+ fn get_rate(+ &self,+ currency: &str,+ ) -> Result<+ f64,+ std::boxed::Box<(dyn std::error::Error + std::marker::Send + std::marker::Sync + 'static)>,+ > {+ match self.rates.get(currency) {+ Some(rate) => Ok(*rate),+ None => Err(anyhow!("No exchange rate for currency: {}", currency).into()),+ }+ }+}++pub enum ExchangeUpdate {+ #[allow(dead_code)] // used in tests+ None,+ AsyncTokio,+}++pub struct Calculator {+ exchange: Arc<Mutex<Arc<CurrencyExchange>>>,+}- if res.get_main_result() == expr {- return Err(Error::CalculatorParse);+impl Calculator {+ pub fn new(exchange_update: ExchangeUpdate) -> Self {+ let exchange = Arc::new(Mutex::new(Arc::new(Default::default())));++ match exchange_update {+ ExchangeUpdate::None => {}+ ExchangeUpdate::AsyncTokio => {+ let exchange_clone = exchange.clone();+ tokio::spawn(async move {+ let mut interval =+ tokio::time::interval(std::time::Duration::from_secs(60 * 60 * 24));++ loop {+ if let Ok(rates) = get_rates().await {+ *exchange_clone.lock().unwrap() = Arc::new(rates);+ }++ interval.tick().await;+ }+ });+ }+ }++ Self { exchange }}- Ok(Calculation {- input: expr.to_string(),- result: res.get_main_result().to_string(),- })+ pub fn try_calculate(&self, expr: &str) -> Result<Calculation, Error> {+ // if expr starts with "d[0-9]+", wrap it in "roll(...)"+ let expr = if DICE_REGEX.is_match(expr) {+ format!("roll({})", expr)+ } else {+ expr.to_string()+ };++ let mut context = fend_core::Context::new();++ let exchange: Arc<CurrencyExchange> = self.exchange.lock().unwrap().clone();++ context.set_exchange_rate_handler_v1(move |currency: &str| exchange.get_rate(currency));++ context.set_random_u32_fn(|| {+ let mut rng = rand::thread_rng();+ rng.gen()+ });++ let res = fend_core::evaluate(&expr, &mut context).map_err(|_| Error::CalculatorParse)?;++ if res.get_main_result() == expr {+ return Err(Error::CalculatorParse);+ }++ Ok(Calculation {+ input: expr.to_string(),+ result: res.get_main_result().to_string(),+ })+ }}#[cfg(test)]@@ -62,15 +173,24 @@ mod tests {#[test]fn it_calculates_simple_expressions() {- assert_eq!(try_calculate("2+2").unwrap().result, 4.0.to_string());- assert_eq!(try_calculate("2*2").unwrap().result, 4.0.to_string());- assert_eq!(try_calculate("2*3").unwrap().result, 6.0.to_string());- assert_eq!(try_calculate("6/2").unwrap().result, 3.0.to_string());+ let calc = Calculator::new(ExchangeUpdate::None);+ assert_eq!(calc.try_calculate("2+2").unwrap().result, 4.0.to_string());+ assert_eq!(calc.try_calculate("2*2").unwrap().result, 4.0.to_string());+ assert_eq!(calc.try_calculate("2*3").unwrap().result, 6.0.to_string());+ assert_eq!(calc.try_calculate("6/2").unwrap().result, 3.0.to_string());}#[test]fn it_respects_paranthesis() {- assert_eq!(try_calculate("2+2*6").unwrap().result, 14.0.to_string());- assert_eq!(try_calculate("(2+2)*6").unwrap().result, 24.0.to_string());+ let calc = Calculator::new(ExchangeUpdate::None);++ assert_eq!(+ calc.try_calculate("2+2*6").unwrap().result,+ 14.0.to_string()+ );+ assert_eq!(+ calc.try_calculate("(2+2)*6").unwrap().result,+ 24.0.to_string()+ );}}diff --git a/core/src/widgets/mod.rs b/core/src/widgets/mod.rsindex a814cd21..99d3852f 100644--- a/core/src/widgets/mod.rs+++ b/core/src/widgets/mod.rs@@ -18,30 +18,37 @@ use serde::{Deserialize, Serialize};use thiserror::Error;use utoipa::ToSchema;-use self::calculator::{try_calculate, Calculation};+use self::calculator::{Calculation, Calculator};pub mod calculator;-pub type Result<T> = std::result::Result<T, Error>;-#[derive(Error, Debug)]pub enum Error {#[error("Calculator parse")]CalculatorParse,}-#[derive(Debug, Serialize, Deserialize, ToSchema)]-#[serde(tag = "type", content = "value", rename_all = "camelCase")]-pub enum Widget {- Calculator(Calculation),+pub struct Widgets {+ calculator: Calculator,}-impl Widget {- pub fn try_new(query: &str) -> Option<Widget> {- Self::calculator(query)+impl Widgets {+ pub fn new() -> Self {+ Self {+ calculator: Calculator::new(calculator::ExchangeUpdate::AsyncTokio),+ }}- fn calculator(query: &str) -> Option<Widget> {- try_calculate(query).ok().map(Widget::Calculator)+ pub fn widget(&self, query: &str) -> Option<Widget> {+ self.calculator+ .try_calculate(query)+ .ok()+ .map(Widget::Calculator)}}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(tag = "type", content = "value", rename_all = "camelCase")]+pub enum Widget {+ Calculator(Calculation),+}diff --git a/frontend/src/lib/api/schema.d.ts b/frontend/src/lib/api/schema.d.tsindex 798f3545..95a7d309 100644--- a/frontend/src/lib/api/schema.d.ts+++ b/frontend/src/lib/api/schema.d.ts@@ -4,11 +4,6 @@*/-/** OneOf type helpers */-type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };-type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;-type OneOf<T extends any[]> = T extends [infer Only] ? Only : T extends [infer A, infer B, ...infer Rest] ? OneOf<[XOR<A, B>, ...Rest]> : never;-export interface paths {"/beta/api/alice": {get: operations["alice_route"];@@ -94,10 +89,8 @@ export interface components {redirectTo: components["schemas"]["UrlWrapper"];};Calculation: {- expr: components["schemas"]["Expr"];input: string;- /** Format: double */- result: number;+ result: string;};CodeOrText: {/** @enum {string} */@@ -185,12 +178,6 @@ export interface components {chosenSites: string[];similarSites: string[];};- Expr: OneOf<[{- /** Format: double */- Number: number;- }, {- Op: Record<string, never>[];- }]>;FactCheckParams: {claim: string;evidence: string;