2022-06-15 21:46:13 +01:00
|
|
|
//use std::net::TcpStream;
|
|
|
|
//use std::io::{Read, Write};
|
2022-06-08 01:05:04 +01:00
|
|
|
|
2022-06-14 01:12:25 +01:00
|
|
|
use wasm_bindgen::prelude::*;
|
|
|
|
use wasm_bindgen::JsCast;
|
2022-06-15 21:46:13 +01:00
|
|
|
use wasm_bindgen_futures::JsFuture;
|
2022-06-14 01:12:25 +01:00
|
|
|
|
2022-06-15 21:46:13 +01:00
|
|
|
//use web_sys::{WebSocket, MessageEvent, ErrorEvent};
|
2022-06-16 02:18:24 +01:00
|
|
|
use js_sys::JsString;
|
2022-06-15 21:46:13 +01:00
|
|
|
use web_sys::{Request, RequestInit, RequestMode, Response};
|
|
|
|
//use wasm_rs_shared_channel::{Expects, spsc::{Receiver, Sender}};
|
2022-06-08 01:05:04 +01:00
|
|
|
|
2022-06-15 21:46:13 +01:00
|
|
|
use usdpl_core::serdes::{Dumpable, Loadable, Primitive};
|
2022-06-16 02:18:24 +01:00
|
|
|
use usdpl_core::socket;
|
2022-06-14 01:12:25 +01:00
|
|
|
|
2022-06-15 21:46:13 +01:00
|
|
|
pub async fn send_js(packet: socket::Packet, port: u16) -> Result<Vec<Primitive>, JsValue> {
|
|
|
|
let mut opts = RequestInit::new();
|
|
|
|
opts.method("POST");
|
|
|
|
opts.mode(RequestMode::Cors);
|
2022-06-14 01:12:25 +01:00
|
|
|
|
2022-06-21 01:03:18 +01:00
|
|
|
let url = format!("http://{}:{}/usdpl/call", socket::HOST_STR, port);
|
2022-06-14 01:12:25 +01:00
|
|
|
|
2022-06-15 21:46:13 +01:00
|
|
|
let mut buffer = [0u8; socket::PACKET_BUFFER_SIZE];
|
2022-06-16 02:18:24 +01:00
|
|
|
let len = packet
|
|
|
|
.dump_base64(&mut buffer)
|
|
|
|
.map_err(super::convert::str_to_js)?;
|
2022-06-15 21:46:13 +01:00
|
|
|
let string: String = String::from_utf8_lossy(&buffer[..len]).into();
|
|
|
|
opts.body(Some(&string.into()));
|
|
|
|
|
|
|
|
let request = Request::new_with_str_and_init(&url, &opts)?;
|
|
|
|
|
2022-06-21 01:03:18 +01:00
|
|
|
//request.headers().set("Accept", "text/base64")?;
|
2022-06-16 02:18:24 +01:00
|
|
|
//.set("Authorization", "wasm TODO_KEY")?;
|
2022-06-15 21:46:13 +01:00
|
|
|
|
|
|
|
let window = web_sys::window().unwrap();
|
|
|
|
let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
|
|
|
|
|
|
|
|
let resp: Response = resp_value.dyn_into()?;
|
|
|
|
let text = JsFuture::from(resp.text()?).await?;
|
|
|
|
let string: JsString = text.dyn_into()?;
|
|
|
|
|
2022-06-16 02:18:24 +01:00
|
|
|
match socket::Packet::load_base64(string.as_string().unwrap().as_bytes())
|
|
|
|
.map_err(super::convert::str_to_js)?
|
|
|
|
.0
|
|
|
|
{
|
|
|
|
socket::Packet::CallResponse(resp) => Ok(resp.response),
|
2022-06-15 21:46:13 +01:00
|
|
|
_ => {
|
2022-06-16 02:18:24 +01:00
|
|
|
//imports::console_warn(&format!("USDPL warning: Got non-call-response message from {}", resp.url()));
|
|
|
|
Err(format!(
|
|
|
|
"Expected call response message from {}, got something else",
|
|
|
|
resp.url()
|
|
|
|
)
|
|
|
|
.into())
|
2022-06-15 21:46:13 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|