66 řádky
1.6 KiB
Rust
66 řádky
1.6 KiB
Rust
use actix::{Actor, ActorContext, Addr, AsyncContext, Handler, StreamHandler};
|
|
use actix_web_actors::ws::{Message as WsMessage, ProtocolError, WebsocketContext};
|
|
use uuid::Uuid;
|
|
|
|
use crate::{
|
|
live_hub::{ConnectMessage, DisconnectMessage, LiveHub, SessionMessage},
|
|
web::tcx::TemplateCtx,
|
|
};
|
|
|
|
pub struct LiveSession {
|
|
pub uuid: Uuid,
|
|
pub thread: (String, i64),
|
|
pub tcx: TemplateCtx,
|
|
pub hub: Addr<LiveHub>,
|
|
}
|
|
|
|
impl Actor for LiveSession {
|
|
type Context = WebsocketContext<Self>;
|
|
}
|
|
|
|
impl Handler<SessionMessage> for LiveSession {
|
|
type Result = ();
|
|
|
|
fn handle(
|
|
&mut self,
|
|
SessionMessage(msg): SessionMessage,
|
|
ctx: &mut Self::Context,
|
|
) -> Self::Result {
|
|
ctx.text(msg)
|
|
}
|
|
}
|
|
|
|
impl StreamHandler<Result<WsMessage, ProtocolError>> for LiveSession {
|
|
fn started(&mut self, ctx: &mut Self::Context) {
|
|
let uuid = self.uuid;
|
|
let thread = self.thread.clone();
|
|
let tcx = self.tcx.clone();
|
|
let recv = ctx.address().recipient();
|
|
|
|
self.hub.do_send(ConnectMessage {
|
|
uuid,
|
|
thread,
|
|
tcx,
|
|
recv,
|
|
});
|
|
}
|
|
|
|
fn handle(&mut self, msg: Result<WsMessage, ProtocolError>, ctx: &mut Self::Context) {
|
|
match msg {
|
|
Ok(WsMessage::Ping(data)) => ctx.pong(&data),
|
|
Ok(WsMessage::Close(_)) => self.finished(ctx),
|
|
_ => (),
|
|
}
|
|
}
|
|
|
|
fn finished(&mut self, ctx: &mut Self::Context) {
|
|
self.hub.do_send(DisconnectMessage {
|
|
uuid: self.uuid,
|
|
thread: self.thread.clone(),
|
|
});
|
|
|
|
ctx.close(None);
|
|
ctx.stop();
|
|
}
|
|
}
|