Skip to content

Commit

Permalink
import JSON files from the NSG webserver via URL
Browse files Browse the repository at this point in the history
  • Loading branch information
tiborschneider committed Sep 25, 2024
1 parent a7f658d commit 53b3d59
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
38 changes: 35 additions & 3 deletions bgpsim-web/src/http_serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,13 @@ use bgpsim::{
types::RouterId,
};
use getrandom::getrandom;
use gloo_net::http::RequestBuilder;
use gloo_utils::window;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use wasm_bindgen::JsCast;
use web_sys::{window, HtmlElement};
use wasm_bindgen_futures::spawn_local;
use web_sys::HtmlElement;
use yewdux::{mrc::Mrc, prelude::Dispatch};

use crate::{
Expand All @@ -36,6 +39,34 @@ use crate::{
state::{Features, Layer, State},
};

/// Import a network by downloading a JSON from an URL
pub fn import_download_json(url: impl AsRef<str>) {
let url = url.as_ref().to_string();
log::debug!("Downloading the network from {url}");
spawn_local(async move {
let json_data = match fetch_json(&url).await {
Ok(x) => x,
Err(e) => {
log::error!("Error fetching the JSON from {url}: {e}");
return;
}
};
log::info!("{json_data}");
import_json_str(json_data);
})
}

pub async fn fetch_json(url: &str) -> Result<String, String> {
RequestBuilder::new(url)
.header("Accept", "application/json")
.send()
.await
.map_err(|e| format!("{e}"))?
.text()
.await
.map_err(|e| format!("Cannot get the body as text: {e}"))
}

/// Import a url data and update the network and settings
pub fn import_url(s: impl AsRef<str>) {
log::debug!("Import http arguments");
Expand Down Expand Up @@ -102,8 +133,9 @@ pub fn export_url() -> String {
let compressed_data = miniz_oxide::deflate::compress_to_vec(json_data.as_bytes(), 8);
let encoded_data = base64::encode_config(compressed_data, base64_config());
let url = window()
.and_then(|w| w.location().href().ok())
.unwrap_or_else(|| String::from("bgpsim.org/"));
.location()
.href()
.unwrap_or_else(|_| String::from("bgpsim.org/"));
format!("{url}?data={encoded_data}")
}

Expand Down
8 changes: 6 additions & 2 deletions bgpsim-web/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use context_menu::Menu;
use draw::{canvas::Canvas, mapping::Map};
use gloo_utils::window;
use header::Header;
use http_serde::import_url;
use http_serde::{import_download_json, import_url};
use sidebar::Sidebar;
use state::State;
use tooltip::Tooltip;
Expand Down Expand Up @@ -127,7 +127,11 @@ fn entry() -> Html {
});
}

if let Some(d) = params.get("data") {
if let Some(file) = params.get("nsg") {
import_download_json(format!(
"https://nsg.ee.ethz.ch/files/public/bgpsim/{file}.json"
))
} else if let Some(d) = params.get("data") {
import_url(d);
}
}
Expand Down

0 comments on commit 53b3d59

Please sign in to comment.