Explorar o código

Exchange rates for the web version, closes #177

David Peter %!s(int64=2) %!d(string=hai) anos
pai
achega
6cbe23366a
Modificáronse 3 ficheiros con 46 adicións e 0 borrados
  1. 5 0
      numbat-wasm/src/lib.rs
  2. 24 0
      numbat-wasm/www/ecb-exchange-rates.php
  3. 17 0
      numbat-wasm/www/index.js

+ 5 - 0
numbat-wasm/src/lib.rs

@@ -40,6 +40,11 @@ impl Numbat {
         Numbat { ctx }
     }
 
+    pub fn set_exchange_rates(&mut self, xml_content: &str) {
+        Context::set_exchange_rates(xml_content);
+        let _ = self.ctx.interpret("use units::currencies", CodeSource::Internal).unwrap();
+    }
+
     pub fn interpret(&mut self, code: &str) -> String {
         let mut output = String::new();
 

+ 24 - 0
numbat-wasm/www/ecb-exchange-rates.php

@@ -0,0 +1,24 @@
+<?php
+$cacheFile = '/tmp/numbat-exchange-rates-cache.xml';
+$cacheTime = 24 * 60 * 60; // 24 hours in seconds
+$ecbUrl = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml';
+
+if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
+    // If cache file is less than 24 hours old, serve it
+    header('Content-Type: text/xml');
+    echo file_get_contents($cacheFile);
+} else {
+    // Else, fetch fresh data and cache it
+    $xmlData = file_get_contents($ecbUrl);
+
+    if ($xmlData) {
+        file_put_contents($cacheFile, $xmlData); // Cache the fetched data
+        header('Content-Type: text/xml');
+        echo $xmlData; // Serve the fetched data
+    } else {
+        // Handle failure in fetching data (e.g., serve cached data even if older than 24 hours or serve an error message)
+        header('HTTP/1.1 500 Internal Server Error');
+        echo "Error fetching the exchange rates.";
+    }
+}
+?>

+ 17 - 0
numbat-wasm/www/index.js

@@ -1,9 +1,26 @@
 import { setup_panic_hook, Numbat } from "numbat-wasm";
 
+async function fetch_exchange_rates() {
+  try {
+      const response = await fetch("https://numbat.dev/ecb-exchange-rates.php");
+
+      if (!response.ok) {
+          return;
+      }
+
+      const xml_content = await response.text();
+      numbat.set_exchange_rates(xml_content);
+  } catch (error) {
+      return;
+  }
+}
+
 setup_panic_hook();
 
 var numbat = Numbat.new();
 
+fetch_exchange_rates();
+
 // Load KeyboardEvent polyfill for old browsers
 keyboardeventKeyPolyfill.polyfill();