Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use serde::{Deserialize, Serialize};
- use serde_json::to_string;
- use std::io::{self, Read};
- use std::str::FromStr;
- use tokio::time::{interval, Duration};
- use futures::StreamExt;
- #[derive(Default)]
- pub struct Extension {
- config: Config,
- }
- #[derive(Default, Debug, Deserialize)]
- struct Config {
- #[serde(rename = "nlExtensionId")]
- pub id: String,
- #[serde(rename = "nlPort", deserialize_with = "from_str")]
- pub port: i32,
- #[serde(rename = "nlToken")]
- pub token: String,
- #[serde(rename = "nlConnectToken")]
- pub connection_token: String,
- }
- impl Config {
- pub fn read_from_stdin() -> Result<Config, String> {
- let mut buffer = String::new();
- let error = io::stdin().read_line(&mut buffer);
- match error {
- Ok(_) => {
- println!("Config received: {}", buffer);
- let config = serde_json::from_str(&buffer);
- let result_error_stringified = config.map_err(|e| e.to_string());
- return result_error_stringified;
- }
- Err(_) => return Err("Error reading from stdin".to_string()),
- }
- }
- }
- impl Extension {
- pub fn new() -> Result<Extension, String> {
- let config = Config::read_from_stdin()?;
- Ok(Extension { config })
- }
- pub fn run(&self) -> Result<(), String> {
- let runtime = tokio::runtime::Runtime::new().map_err(|e| e.to_string())?;
- runtime.block_on(self.message_handler());
- Ok(())
- }
- async fn message_handler(&self) -> Result<(), String> {
- let url = format!("ws://localhost:{}", self.config.port);
- let (mut ws_stream, _) = tokio_tungstenite::connect_async(url)
- .await
- .map_err(|e| e.to_string())?;
- loop {
- tokio::select! {
- Some(msg) = ws_stream.next() => {
- print!("message received: {}", msg.unwrap())
- }
- }
- }
- }
- }
- // helper function to deserialize a string into an integer
- fn from_str<'de, T, D>(deserializer: D) -> Result<T, D::Error>
- where
- T: FromStr,
- T::Err: std::fmt::Display,
- D: serde::Deserializer<'de>,
- {
- let s = String::deserialize(deserializer)?;
- T::from_str(&s).map_err(serde::de::Error::custom)
- }
Advertisement
Add Comment
Please, Sign In to add comment