nekrochan/src/live_session.rs

69 řádky
1.8 KiB
Rust

use actix::{Actor, ActorContext, Addr, AsyncContext, Handler, StreamHandler};
use actix_web_actors::ws::{Message as WsMessage, ProtocolError, WebsocketContext};
use serde_json::json;
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, msg: SessionMessage, ctx: &mut Self::Context) -> Self::Result {
match msg {
SessionMessage::Data(data) => ctx.text(data),
SessionMessage::Stop => {
ctx.text(json!({ "type": "thread_removed" }).to_string());
self.finished(ctx)
}
};
}
}
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();
}
}