Skip to content

Commit

Permalink
Messaging
Browse files Browse the repository at this point in the history
  • Loading branch information
nanoqsh committed May 30, 2022
1 parent 318d1ca commit 890137e
Show file tree
Hide file tree
Showing 14 changed files with 111 additions and 54 deletions.
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,10 @@ name = "voki"
version = "0.1.0"
edition = "2021"

[dev-dependencies]
http = { path = "./http" }
server = { path = "./server" }
web = { path = "./web" }

[dependencies]
termion = "1.5"
File renamed without changes.
2 changes: 1 addition & 1 deletion base/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
pub mod abi;
pub mod api;
mod code;

pub use self::code::{decode, encode};
16 changes: 16 additions & 0 deletions http/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use rocket::{
get,
serde::{json::Json, Serialize},
};

#[derive(Serialize)]
#[serde(crate = "rocket::serde")]
pub struct Message<'a> {
text: &'a str,
}

#[get("/")]
pub async fn index() -> Json<Message<'static>> {
let message = Message { text: "hello" };
message.into()
}
19 changes: 2 additions & 17 deletions http/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,5 @@
use rocket::{
fs::FileServer,
get, launch, routes,
serde::{json::Json, Serialize},
};

#[derive(Serialize)]
#[serde(crate = "rocket::serde")]
struct Message<'a> {
text: &'a str,
}

#[get("/")]
fn index() -> Json<Message<'static>> {
let message = Message { text: "hello" };
message.into()
}
use http::index;
use rocket::{fs::FileServer, launch, routes};

#[launch]
fn rocket() -> _ {
Expand Down
18 changes: 18 additions & 0 deletions server/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
mod args;
mod event;
mod listen;
mod manage;

use self::{args::Args, listen::listen, manage::manage};
use tokio::sync::mpsc;

pub async fn run() {
use clap::Parser;

let args = Args::parse();

let (sender, receiver) = mpsc::channel(16);
let listen = tokio::spawn(listen(args.address(), sender));
let manage = tokio::spawn(manage(receiver));
let _ = tokio::join!(listen, manage);
}
17 changes: 2 additions & 15 deletions server/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,6 @@
mod args;
mod event;
mod listen;
mod manage;

use self::{args::Args, listen::listen, manage::manage};
use tokio::sync::mpsc;
use server::run;

#[tokio::main]
async fn main() {
use clap::Parser;

let args = Args::parse();

let (sender, receiver) = mpsc::channel(16);
let listen = tokio::spawn(listen(args.address(), sender));
let manage = tokio::spawn(manage(receiver));
let _ = tokio::join!(listen, manage);
run().await;
}
20 changes: 13 additions & 7 deletions server/src/manage.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::event::*;
use base::{abi, decode, encode};
use base::{api, decode, encode};
use std::{
collections::{hash_map::Entry, HashMap},
net::SocketAddr,
Expand Down Expand Up @@ -103,7 +103,7 @@ impl Channels {
}

pub async fn manage(mut receiver: Receiver<Event>) -> ! {
use abi::*;
use api::*;

struct Client {
sender: Sender<Vec<u8>>,
Expand Down Expand Up @@ -164,11 +164,17 @@ pub async fn manage(mut receiver: Receiver<Event>) -> ! {
let name = &user.name;
println!("{name} ({chan}): {text}");

ServerMessage::Said {
from: id,
chan,
text,
// Send this to all
for client in clients.values() {
let message = ServerMessage::Said {
from: id,
chan,
text,
};
send(&client.sender, message).await;
}

continue;
}
None => ServerMessage::Closed,
},
Expand Down Expand Up @@ -211,7 +217,7 @@ pub async fn manage(mut receiver: Receiver<Event>) -> ! {
}
}

async fn send(sender: &Sender<Vec<u8>>, message: abi::ServerMessage<'_>) {
async fn send(sender: &Sender<Vec<u8>>, message: api::ServerMessage<'_>) {
let mut buf = Vec::with_capacity(64);
encode(&message, &mut buf).expect("encode");
let _ = sender.send(buf).await;
Expand Down
17 changes: 17 additions & 0 deletions src/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,20 @@ macro_rules! info {
}

pub(crate) use info;

macro_rules! error {
($e:expr) => {
use termion::{color, style};

println!(
"{}{}error{}{}: {}",
color::Fg(color::Red),
style::Bold,
color::Fg(color::Reset),
style::Reset,
$e
);
};
}

pub(crate) use error;
9 changes: 7 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mod info;
mod tools;

use self::{info::info, tools::*};
use self::{info::*, tools::*};
use std::{env, process::Command};

fn main() {
Expand Down Expand Up @@ -30,13 +30,18 @@ fn main() {
for Dependency { name, tool } in deps {
info!("Building", name);

Command::new(tool)
let status = Command::new(tool)
.args(tool.args())
.args(release.then(|| "--release"))
.current_dir(name)
.spawn()
.expect("build")
.wait()
.expect("wait");

if !status.success() {
error!("building failed");
break;
}
}
}
26 changes: 20 additions & 6 deletions web/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ mod view;

use self::{
socket::socket,
state::{Channel, Message, State},
view::{App, Data, Event, Props},
state::{Channel, Message, State, User},
view::{Action, App, Data, Event, Props},
};
use std::{cell::RefCell, rc::Rc};
use wasm_bindgen::prelude::*;
Expand All @@ -27,11 +27,11 @@ impl View {

#[wasm_bindgen(start)]
pub fn main() -> Result<(), JsValue> {
use base::abi::{ClientMessage, ServerMessage};
use base::api::{ClientMessage, ServerMessage};
use gloo::console::log;
use yew::Callback;

let (write, read) = socket("ws://127.0.0.1:4567");
let (write, read) = socket("ws://0.0.0.0:4567");
write.request(ClientMessage::Login {
name: "nano",
pass: "nano",
Expand All @@ -52,7 +52,11 @@ pub fn main() -> Result<(), JsValue> {
current_channel: 0,
me: 0,
},
onaction: Callback::from(|_| todo!()),
onaction: Callback::from(move |action| match action {
Action::Send { chan, text } => {
write.request(ClientMessage::Say { chan, text: &text })
}
}),
},
);

Expand All @@ -65,7 +69,17 @@ pub fn main() -> Result<(), JsValue> {
Ok(id) => log!("logged", id),
Err(err) => log!("error", err.to_string()),
},
ServerMessage::User(_) => log!("user"),
ServerMessage::User(user) => {
state.borrow_mut().push_user(
user.id,
User {
name: user.name.into(),
avatar: user.avatar.map(Into::into),
},
);

view.update();
}
ServerMessage::Channel(chan) => {
state
.borrow_mut()
Expand Down
6 changes: 3 additions & 3 deletions web/src/socket.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::post::{post, Receiver, Sender};
use base::{abi, decode, encode};
use base::{api, decode, encode};
use futures::{SinkExt, StreamExt};
use gloo::{
console::error,
Expand All @@ -11,7 +11,7 @@ use std::time::Duration;
pub struct Write(Sender<Message>);

impl Write {
pub fn request(&self, message: abi::ClientMessage) {
pub fn request(&self, message: api::ClientMessage) {
let mut buf = Vec::with_capacity(64);
encode(&message, &mut buf).expect("encode");
self.0.push(Message::Bytes(buf));
Expand All @@ -23,7 +23,7 @@ pub struct Read(Receiver<Message>);
impl Read {
pub fn register<F>(self, mut callback: F)
where
F: FnMut(abi::ServerMessage) + 'static,
F: FnMut(api::ServerMessage) + 'static,
{
wasm_futures::spawn_local(async move {
loop {
Expand Down
6 changes: 5 additions & 1 deletion web/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ impl Channel {
pub fn new(name: &str, icon: Option<&str>) -> Self {
Self {
name: name.into(),
icon: icon.map(|icon| icon.into()),
icon: icon.map(Into::into),
messages: Vector::default(),
}
}
Expand Down Expand Up @@ -146,4 +146,8 @@ impl State {
chan.messages.push_back(message);
}
}

pub fn push_user(&mut self, id: u32, user: User) {
self.users.insert(id, user);
}
}
4 changes: 2 additions & 2 deletions web/src/view/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub enum Event {
}

pub enum Action {
Send { channel: u32, text: Rc<str> },
Send { chan: u32, text: Rc<str> },
}

#[derive(PartialEq, Properties)]
Expand Down Expand Up @@ -57,7 +57,7 @@ impl Component for App {

let onsend = Callback::from({
let onaction = ctx.props().onaction.clone();
move |(channel, text)| onaction.emit(Action::Send { channel, text })
move |(chan, text)| onaction.emit(Action::Send { chan, text })
});

html! {
Expand Down

0 comments on commit 890137e

Please sign in to comment.