monxa

Untitled

Oct 30th, 2024
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.29 KB | None | 0 0
  1. use serde::{Deserialize, Serialize};
  2. use serde_json::to_string;
  3. use std::io::{self, Read};
  4. use std::str::FromStr;
  5. use tokio::time::{interval, Duration};
  6. use futures::StreamExt;
  7.  
  8. #[derive(Default)]
  9. pub struct Extension {
  10.     config: Config,
  11. }
  12.  
  13. #[derive(Default, Debug, Deserialize)]
  14. struct Config {
  15.     #[serde(rename = "nlExtensionId")]
  16.     pub id: String,
  17.     #[serde(rename = "nlPort", deserialize_with = "from_str")]
  18.     pub port: i32,
  19.     #[serde(rename = "nlToken")]
  20.     pub token: String,
  21.     #[serde(rename = "nlConnectToken")]
  22.     pub connection_token: String,
  23. }
  24.  
  25. impl Config {
  26.     pub fn read_from_stdin() -> Result<Config, String> {
  27.         let mut buffer = String::new();
  28.         let error = io::stdin().read_line(&mut buffer);
  29.         match error {
  30.             Ok(_) => {
  31.                 println!("Config received: {}", buffer);
  32.                 let config = serde_json::from_str(&buffer);
  33.                 let result_error_stringified = config.map_err(|e| e.to_string());
  34.                 return result_error_stringified;
  35.             }
  36.             Err(_) => return Err("Error reading from stdin".to_string()),
  37.         }
  38.     }
  39. }
  40.  
  41. impl Extension {
  42.     pub fn new() -> Result<Extension, String> {
  43.         let config = Config::read_from_stdin()?;
  44.         Ok(Extension { config })
  45.     }
  46.     pub fn run(&self) -> Result<(), String> {
  47.         let runtime = tokio::runtime::Runtime::new().map_err(|e| e.to_string())?;
  48.         runtime.block_on(self.message_handler());
  49.         Ok(())
  50.     }
  51.     async fn message_handler(&self) -> Result<(), String> {
  52.         let url = format!("ws://localhost:{}", self.config.port);
  53.         let (mut ws_stream, _) = tokio_tungstenite::connect_async(url)
  54.             .await
  55.             .map_err(|e| e.to_string())?;
  56.         loop {
  57.             tokio::select! {
  58.                 Some(msg) = ws_stream.next() => {
  59.                     print!("message received: {}", msg.unwrap())
  60.                 }
  61.             }
  62.         }
  63.     }
  64. }
  65.  
  66. // helper function to deserialize a string into an integer
  67. fn from_str<'de, T, D>(deserializer: D) -> Result<T, D::Error>
  68. where
  69.    T: FromStr,
  70.    T::Err: std::fmt::Display,
  71.    D: serde::Deserializer<'de>,
  72. {
  73.     let s = String::deserialize(deserializer)?;
  74.     T::from_str(&s).map_err(serde::de::Error::custom)
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment