From 9993d2d99186afdeffffe10449c27be439db9456 Mon Sep 17 00:00:00 2001 From: Daniel Sanchez Date: Wed, 19 Oct 2022 15:58:09 +0200 Subject: [PATCH] Chat example (#11) * Added main skeleton for toy-chat example * Implement chat example main block * Polish chat and add necessary fixes * Added author info to crates --- examples/Cargo.toml | 5 + examples/toy-chat/Cargo.toml | 17 ++ examples/toy-chat/src/main.rs | 305 ++++++++++++++++++++++++++++++ examples/toy-chat/src/protocol.rs | 42 ++++ waku-sys/Cargo.toml | 3 + waku/Cargo.toml | 4 +- waku/src/events/mod.rs | 1 + waku/src/general/mod.rs | 1 + waku/src/lib.rs | 8 +- waku/src/node/mod.rs | 10 +- waku/src/node/peers.rs | 2 +- waku/src/node/store.rs | 16 +- 12 files changed, 397 insertions(+), 17 deletions(-) create mode 100644 examples/Cargo.toml create mode 100644 examples/toy-chat/Cargo.toml create mode 100644 examples/toy-chat/src/main.rs create mode 100644 examples/toy-chat/src/protocol.rs diff --git a/examples/Cargo.toml b/examples/Cargo.toml new file mode 100644 index 0000000..0ea93d3 --- /dev/null +++ b/examples/Cargo.toml @@ -0,0 +1,5 @@ +[workspace] + +members = [ + "toy-chat" +] \ No newline at end of file diff --git a/examples/toy-chat/Cargo.toml b/examples/toy-chat/Cargo.toml new file mode 100644 index 0000000..dbf4d95 --- /dev/null +++ b/examples/toy-chat/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "toy-chat" +version = "0.1.0" +edition = "2021" +authors = [ + "Daniel Sanchez Quiros " +] +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +waku = { path = "../../waku" } +tui = "0.19" +crossterm = "0.25" +unicode-width = "0.1" +prost = "0.11" +once_cell = "1.15" +chrono = "0.4" \ No newline at end of file diff --git a/examples/toy-chat/src/main.rs b/examples/toy-chat/src/main.rs new file mode 100644 index 0000000..42906c0 --- /dev/null +++ b/examples/toy-chat/src/main.rs @@ -0,0 +1,305 @@ +mod protocol; + +use crate::protocol::{Chat2Message, TOY_CHAT_CONTENT_TOPIC}; +use chrono::Utc; +use crossterm::{ + event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode}, + execute, + terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, +}; +use prost::Message; +use std::io::Write; +use std::str::FromStr; +use std::sync::{Arc, RwLock}; +use std::time::Duration; +use std::{error::Error, io}; +use tui::{ + backend::{Backend, CrosstermBackend}, + layout::{Constraint, Direction, Layout}, + style::{Color, Modifier, Style}, + text::{Span, Spans, Text}, + widgets::{Block, Borders, List, ListItem, Paragraph}, + Frame, Terminal, +}; +use unicode_width::UnicodeWidthStr; +use waku::{ + waku_new, waku_set_event_callback, ContentFilter, Multiaddr, PagingOptions, ProtocolId, + Running, StoreQuery, WakuMessage, WakuNodeHandle, +}; + +enum InputMode { + Normal, + Editing, +} + +const NODES: &[&str] = &[ + "/dns4/node-01.ac-cn-hongkong-c.wakuv2.test.statusim.net/tcp/30303/p2p/16Uiu2HAkvWiyFsgRhuJEb9JfjYxEkoHLgnUQmr1N5mKWnYjxYRVm", + "/dns4/node-01.do-ams3.wakuv2.test.statusim.net/tcp/30303/p2p/16Uiu2HAmPLe7Mzm8TsYUubgCAW1aJoeFScxrLj8ppHFivPo97bUZ", + "/dns4/node-01.gc-us-central1-a.wakuv2.test.statusim.net/tcp/30303/p2p/16Uiu2HAmJb2e28qLXxT5kZxVUUoJt72EMzNGXB47Rxx5hw3q4YjS" +]; + +/// App holds the state of the application +struct App { + /// Current value of the input box + input: String, + nick: String, + /// Current input mode + input_mode: InputMode, + /// History of recorded messages + messages: Arc>>, + + node_handle: WakuNodeHandle, +} + +impl App { + fn new(nick: String, node_handle: WakuNodeHandle) -> App { + App { + input: String::new(), + input_mode: InputMode::Normal, + messages: Arc::new(RwLock::new(Vec::new())), + node_handle, + nick, + } + } +} +fn retrieve_history(node_handle: &WakuNodeHandle) -> waku::Result> { + let self_id = node_handle.peer_id().unwrap(); + let peer = node_handle + .peers()? + .iter() + .cloned() + .find(|peer| peer.peer_id() != &self_id) + .unwrap(); + + let result = node_handle.store_query( + &StoreQuery { + pubsub_topic: None, + content_filters: vec![ContentFilter::new(TOY_CHAT_CONTENT_TOPIC.clone())], + start_time: Some( + (Duration::from_secs(Utc::now().timestamp() as u64) + - Duration::from_secs(60 * 60 * 24)) + .as_nanos() as usize, + ), + end_time: None, + paging_options: Some(PagingOptions { + page_size: 25, + cursor: None, + forward: true, + }), + }, + peer.peer_id(), + Some(Duration::from_secs(10)), + )?; + + Ok(result + .messages() + .iter() + .map(|waku_message| { + ::decode(waku_message.payload()) + .expect("Toy chat messages should be decodeable") + }) + .collect()) +} +fn setup_node_handle() -> std::result::Result, Box> { + let node_handle = waku_new(None)?; + let node_handle = node_handle.start()?; + for address in NODES.iter().map(|a| Multiaddr::from_str(a).unwrap()) { + let peerid = node_handle.add_peer(&address, ProtocolId::Relay)?; + node_handle.connect_peer_with_id(peerid, None)?; + } + node_handle.relay_subscribe(None)?; + Ok(node_handle) +} + +fn main() -> std::result::Result<(), Box> { + let nick = std::env::args().nth(1).expect("Nick to be set"); + // setup terminal + enable_raw_mode()?; + let mut stdout = io::stdout(); + execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?; + let backend = CrosstermBackend::new(stdout); + let mut terminal = Terminal::new(backend)?; + + let node_handle = setup_node_handle()?; + + // create app and run it + let mut app = App::new(nick, node_handle); + let history = retrieve_history(&app.node_handle)?; + if !history.is_empty() { + *app.messages.write().unwrap() = history; + } + let shared_messages = Arc::clone(&app.messages); + waku_set_event_callback(move |signal| match signal.event() { + waku::Event::WakuMessage(event) => { + match ::decode(event.waku_message().payload()) { + Ok(chat_message) => { + shared_messages.write().unwrap().push(chat_message); + } + Err(e) => { + let mut out = std::io::stderr(); + write!(out, "{:?}", e).unwrap(); + } + } + } + waku::Event::Unrecognized(data) => { + let mut out = std::io::stderr(); + write!(out, "Error, received unrecognized event {data}").unwrap(); + } + _ => {} + }); + + // app.node_handle.relay_publish_message(&WakuMessage::new(Chat2Message::new(&app.nick, format!("")))) + let res = run_app(&mut terminal, &mut app); + + // restore terminal + disable_raw_mode()?; + execute!( + terminal.backend_mut(), + LeaveAlternateScreen, + DisableMouseCapture + )?; + terminal.show_cursor()?; + app.node_handle.stop()?; + + if let Err(err) = res { + println!("{:?}", err) + } + Ok(()) +} + +fn run_app( + terminal: &mut Terminal, + app: &mut App, +) -> std::result::Result<(), Box> { + loop { + terminal.draw(|f| ui(f, app))?; + + if let Event::Key(key) = event::read()? { + match app.input_mode { + InputMode::Normal => match key.code { + KeyCode::Char('e') => { + app.input_mode = InputMode::Editing; + } + KeyCode::Char('q') => { + return Ok(()); + } + _ => {} + }, + InputMode::Editing => match key.code { + KeyCode::Enter => { + let message_content: String = app.input.drain(..).collect(); + let message = Chat2Message::new(&app.nick, &message_content); + let mut buff = Vec::new(); + Message::encode(&message, &mut buff)?; + let waku_message = WakuMessage::new( + buff, + TOY_CHAT_CONTENT_TOPIC.clone(), + 1, + Utc::now().timestamp() as usize, + ); + if let Err(e) = + app.node_handle + .relay_publish_message(&waku_message, None, None) + { + let mut out = std::io::stderr(); + write!(out, "{:?}", e).unwrap(); + } + } + KeyCode::Char(c) => { + app.input.push(c); + } + KeyCode::Backspace => { + app.input.pop(); + } + KeyCode::Esc => { + app.input_mode = InputMode::Normal; + } + _ => {} + }, + } + } + } +} + +fn ui(f: &mut Frame, app: &App) { + let chunks = Layout::default() + .direction(Direction::Vertical) + .margin(2) + .constraints( + [ + Constraint::Length(1), + Constraint::Length(3), + Constraint::Min(1), + ] + .as_ref(), + ) + .split(f.size()); + + let (msg, style) = match app.input_mode { + InputMode::Normal => ( + vec![ + Span::raw("Press "), + Span::styled("q", Style::default().add_modifier(Modifier::BOLD)), + Span::raw(" to exit, "), + Span::styled("e", Style::default().add_modifier(Modifier::BOLD)), + Span::raw(" to start writing a message."), + ], + Style::default().add_modifier(Modifier::RAPID_BLINK), + ), + InputMode::Editing => ( + vec![ + Span::raw("Press "), + Span::styled("Esc", Style::default().add_modifier(Modifier::BOLD)), + Span::raw(" to stop editing, "), + Span::styled("Enter", Style::default().add_modifier(Modifier::BOLD)), + Span::raw(" to record the message"), + ], + Style::default(), + ), + }; + let mut text = Text::from(Spans::from(msg)); + text.patch_style(style); + let help_message = Paragraph::new(text); + f.render_widget(help_message, chunks[0]); + + let input = Paragraph::new(app.input.as_ref()) + .style(match app.input_mode { + InputMode::Normal => Style::default(), + InputMode::Editing => Style::default().fg(Color::Yellow), + }) + .block(Block::default().borders(Borders::ALL).title("Input")); + f.render_widget(input, chunks[1]); + match app.input_mode { + InputMode::Normal => + // Hide the cursor. `Frame` does this by default, so we don't need to do anything here + {} + + InputMode::Editing => { + // Make the cursor visible and ask tui-rs to put it at the specified coordinates after rendering + f.set_cursor( + // Put cursor past the end of the input text + chunks[1].x + app.input.width() as u16 + 1, + // Move one line down, from the border to the input line + chunks[1].y + 1, + ) + } + } + + let messages: Vec = app + .messages + .read() + .unwrap() + .iter() + .map(|message| { + let content = vec![Spans::from(Span::raw(format!( + "[{} - {}]: {}", + message.timestamp().format("%d-%m-%y %H:%M"), + message.nick(), + message.message() + )))]; + ListItem::new(content) + }) + .collect(); + let messages = List::new(messages).block(Block::default().borders(Borders::ALL).title("Chat")); + f.render_widget(messages, chunks[2]); +} diff --git a/examples/toy-chat/src/protocol.rs b/examples/toy-chat/src/protocol.rs new file mode 100644 index 0000000..110747e --- /dev/null +++ b/examples/toy-chat/src/protocol.rs @@ -0,0 +1,42 @@ +use chrono::{DateTime, TimeZone, Utc}; +use once_cell::sync::Lazy; +use prost::Message; +use waku::{Encoding, WakuContentTopic}; + +pub static TOY_CHAT_CONTENT_TOPIC: Lazy = Lazy::new(|| WakuContentTopic { + application_name: "toy-chat".into(), + version: 2, + content_topic_name: "huilong".into(), + encoding: Encoding::Proto, +}); + +#[derive(Clone, Message)] +pub struct Chat2Message { + #[prost(uint64, tag = "1")] + timestamp: u64, + #[prost(string, tag = "2")] + nick: String, + #[prost(bytes, tag = "3")] + payload: Vec, +} + +impl Chat2Message { + pub fn new(nick: &str, payload: &str) -> Self { + Self { + timestamp: Utc::now().timestamp() as u64, + nick: nick.to_string(), + payload: payload.as_bytes().to_vec(), + } + } + pub fn message(&self) -> String { + String::from_utf8(self.payload.clone()).unwrap() + } + + pub fn nick(&self) -> &str { + &self.nick + } + + pub fn timestamp(&self) -> DateTime { + Utc.timestamp(self.timestamp as i64, 0) + } +} diff --git a/waku-sys/Cargo.toml b/waku-sys/Cargo.toml index 5239a44..92dac0a 100644 --- a/waku-sys/Cargo.toml +++ b/waku-sys/Cargo.toml @@ -2,6 +2,9 @@ name = "waku-sys" version = "0.1.0" edition = "2021" +authors = [ + "Daniel Sanchez Quiros " +] [lib] crate-type = ["rlib"] diff --git a/waku/Cargo.toml b/waku/Cargo.toml index 6ad01da..57b7b8c 100644 --- a/waku/Cargo.toml +++ b/waku/Cargo.toml @@ -2,7 +2,9 @@ name = "waku" version = "0.1.0" edition = "2021" - +authors = [ + "Daniel Sanchez Quiros " +] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/waku/src/events/mod.rs b/waku/src/events/mod.rs index 73bf28a..08b728b 100644 --- a/waku/src/events/mod.rs +++ b/waku/src/events/mod.rs @@ -38,6 +38,7 @@ impl Signal { #[serde(untagged, rename_all = "camelCase")] pub enum Event { WakuMessage(WakuMessageEvent), + Unrecognized(serde_json::Value), } /// Type of `event` field for a `message` event diff --git a/waku/src/general/mod.rs b/waku/src/general/mod.rs index 5e645c0..a152520 100644 --- a/waku/src/general/mod.rs +++ b/waku/src/general/mod.rs @@ -239,6 +239,7 @@ pub struct StoreQuery { #[serde(rename_all = "camelCase")] pub struct StoreResponse { /// Array of retrieved historical messages in [`WakuMessage`] format + #[serde(default)] messages: Vec, /// Paging information in [`PagingOptions`] format from which to resume further historical queries paging_options: Option, diff --git a/waku/src/lib.rs b/waku/src/lib.rs index 968819b..109cdb3 100644 --- a/waku/src/lib.rs +++ b/waku/src/lib.rs @@ -8,14 +8,14 @@ mod node; pub use node::{ waku_create_content_topic, waku_create_pubsub_topic, waku_dafault_pubsub_topic, waku_new, - waku_store_query, Initialized, Protocol, Running, WakuNodeConfig, WakuNodeHandle, WakuPeerData, - WakuPeers, + waku_store_query, Aes256Gcm, Initialized, Key, Multiaddr, Protocol, PublicKey, Running, + SecretKey, WakuNodeConfig, WakuNodeHandle, WakuPeerData, WakuPeers, }; pub use general::{ ContentFilter, DecodedPayload, Encoding, FilterSubscription, MessageId, MessageIndex, - PagingOptions, PeerId, ProtocolId, StoreQuery, StoreResponse, WakuContentTopic, WakuMessage, - WakuMessageVersion, WakuPubSubTopic, + PagingOptions, PeerId, ProtocolId, Result, StoreQuery, StoreResponse, WakuContentTopic, + WakuMessage, WakuMessageVersion, WakuPubSubTopic, }; pub use events::{waku_set_event_callback, Event, Signal, WakuMessageEvent}; diff --git a/waku/src/node/mod.rs b/waku/src/node/mod.rs index 9ad554b..e98eff9 100644 --- a/waku/src/node/mod.rs +++ b/waku/src/node/mod.rs @@ -9,9 +9,9 @@ mod relay; mod store; // std -use aes_gcm::{Aes256Gcm, Key}; -use multiaddr::Multiaddr; -use secp256k1::{PublicKey, SecretKey}; +pub use aes_gcm::{Aes256Gcm, Key}; +pub use multiaddr::Multiaddr; +pub use secp256k1::{PublicKey, SecretKey}; use std::marker::PhantomData; use std::sync::Mutex; use std::time::Duration; @@ -232,8 +232,8 @@ impl WakuNodeHandle { pub fn store_query( &self, query: &StoreQuery, - peer_id: PeerId, - timeout: Duration, + peer_id: &PeerId, + timeout: Option, ) -> Result { store::waku_store_query(query, peer_id, timeout) } diff --git a/waku/src/node/peers.rs b/waku/src/node/peers.rs index dea603f..dcd7abb 100644 --- a/waku/src/node/peers.rs +++ b/waku/src/node/peers.rs @@ -125,7 +125,7 @@ pub fn waku_peer_count() -> Result { pub type Protocol = String; /// Peer data from known/connected waku nodes -#[derive(Deserialize)] +#[derive(Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct WakuPeerData { /// Waku peer id diff --git a/waku/src/node/store.rs b/waku/src/node/store.rs index cc39a7d..818b10e 100644 --- a/waku/src/node/store.rs +++ b/waku/src/node/store.rs @@ -13,8 +13,8 @@ use crate::general::{JsonResponse, PeerId, Result, StoreQuery, StoreResponse}; /// These [`PagingOptions`](`crate::general::PagingOptions`) must contain a cursor pointing to the Index from which a new page can be requested pub fn waku_store_query( query: &StoreQuery, - peer_id: PeerId, - timeout: Duration, + peer_id: &PeerId, + timeout: Option, ) -> Result { let result = unsafe { CStr::from_ptr(waku_sys::waku_store_query( @@ -24,13 +24,17 @@ pub fn waku_store_query( ) .expect("CString should build properly from the serialized filter subscription") .into_raw(), - CString::new(peer_id) + CString::new(peer_id.clone()) .expect("CString should build properly from peer id") .into_raw(), timeout - .as_millis() - .try_into() - .expect("Duration as milliseconds should fit in a i32"), + .map(|timeout| { + timeout + .as_millis() + .try_into() + .expect("Duration as milliseconds should fit in a i32") + }) + .unwrap_or(0), )) } .to_str()