Skip to content

Commit

Permalink
ws::res > add MessageType::Command and support fns & callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
canewsin committed Jan 20, 2024
1 parent 18820b8 commit 0980b6c
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 2 deletions.
2 changes: 2 additions & 0 deletions src/plugins/websocket/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::collections::HashMap;
use actix::prelude::*;
use log::*;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::core::{error::Error, site::models::SiteInfo};

Expand Down Expand Up @@ -38,6 +39,7 @@ impl Handler<RegisterWSClient> for WebsocketController {
pub enum ServerEvent {
Event { cmd: String, params: EventType },
Notification { cmd: String, params: Value },
Confirm { cmd: String, params: Value },
}

#[allow(clippy::enum_variant_names)]
Expand Down
38 changes: 37 additions & 1 deletion src/plugins/websocket/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub mod request;
pub mod response;

use futures::executor::block_on;
use serde_json::json;
use serde_json::{json, Value};

use std::collections::HashMap;

Expand Down Expand Up @@ -100,6 +100,8 @@ pub async fn serve_websocket(
site_addr: addr,
address,
channels: vec![],
next_message_id: 0,
waiting_callbacks: HashMap::new(),
};
let (addr, res) = WsResponseBuilder::new(websocket, &req, stream)
.start_with_addr()
Expand All @@ -108,13 +110,17 @@ pub async fn serve_websocket(
Ok(res)
}

type WaitingCallback = Box<dyn FnOnce(&mut ZeruWebsocket, serde_json::Value) -> ()>;

pub struct ZeruWebsocket {
site_controller: Addr<SitesController>,
user_controller: Addr<UserController>,
ws_controller: Addr<WebsocketController>,
site_addr: actix::Addr<Site>,
address: Address,
channels: Vec<String>,
next_message_id: usize,
waiting_callbacks: HashMap<usize, WaitingCallback>,
}

impl Actor for ZeruWebsocket {
Expand Down Expand Up @@ -284,6 +290,33 @@ impl ZeruWebsocket {
Ok(())
}

fn cmd(
&mut self,
cmd: &str,
params: Value,
callback: Option<WaitingCallback>,
) -> Result<(), Error> {
let id = self.next_message_id;
self.next_message_id += 1;
if let Some(callback) = callback {
self.waiting_callbacks.insert(id, callback);
}
match cmd {
"confirm" => {
self.confirm(params);
return Ok(());
}
_ => unimplemented!("Command not implemented: {}", cmd),
}
}

fn confirm(&mut self, params: Value) {
self.ws_controller.do_send(ServerEvent::Confirm {
cmd: "confirm".to_string(),
params,
});
}

fn is_admin_site(&mut self) -> Result<bool, Error> {
let site = block_on(self.site_addr.send(SiteInfoRequest {}))??;
let res = site
Expand Down Expand Up @@ -368,6 +401,9 @@ impl ZeruWebsocket {
// });
};
let mut msg = response?;
if msg.is_command() {
return Ok(());
}
self.respond(ctx, &mut msg)
}

Expand Down
5 changes: 5 additions & 0 deletions src/plugins/websocket/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,9 @@ impl Command {
let resp = Message::inject_script(self.id, serde_json::to_value(body)?);
Ok(resp)
}

pub fn command(&self) -> Result<Message, Error> {
let resp = Message::command();
Ok(resp)
}
}
17 changes: 16 additions & 1 deletion src/plugins/websocket/response.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use serde::{Deserialize, Serialize};
use serde_json::json;

use crate::utils::is_default;

Expand All @@ -12,9 +13,10 @@ pub struct Message {
result: serde_json::Value,
}

#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum MessageType {
Command,
InjectScript,
Response,
Error,
Expand All @@ -39,4 +41,17 @@ impl Message {
id: 0,
}
}

pub fn is_command(&self) -> bool {
self.cmd == MessageType::Command
}

pub fn command() -> Message {
Message {
cmd: MessageType::Command,
to: 0,
result: json!(null),
id: 0,
}
}
}

0 comments on commit 0980b6c

Please sign in to comment.