1 extern crate lemmy_server;
3 extern crate diesel_migrations;
6 use actix_files::NamedFile;
8 use actix_web_actors::ws;
9 use lemmy_server::db::establish_connection;
10 use lemmy_server::websocket::server::*;
12 use std::time::{Duration, Instant};
16 /// How often heartbeat pings are sent
17 const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
18 /// How long before lack of client response causes a timeout
19 const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
21 /// Entry point for our route
25 chat_server: web::Data<Addr<ChatServer>>,
26 ) -> Result<HttpResponse, Error> {
29 cs_addr: chat_server.get_ref().to_owned(),
35 .unwrap_or("127.0.0.1:12345")
38 .unwrap_or("127.0.0.1")
47 cs_addr: Addr<ChatServer>,
51 /// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT),
52 /// otherwise we drop connection.
56 impl Actor for WSSession {
57 type Context = ws::WebsocketContext<Self>;
59 /// Method is called on actor start.
60 /// We register ws session with ChatServer
61 fn started(&mut self, ctx: &mut Self::Context) {
62 // we'll start heartbeat process on session start.
65 // register self in chat server. `AsyncContext::wait` register
66 // future within context, but context waits until this future resolves
67 // before processing any other events.
68 // across all routes within application
69 let addr = ctx.address();
72 addr: addr.recipient(),
73 ip: self.ip.to_owned(),
76 .then(|res, act, ctx| {
78 Ok(res) => act.id = res,
79 // something is wrong with chat server
87 fn stopping(&mut self, _ctx: &mut Self::Context) -> Running {
89 self.cs_addr.do_send(Disconnect {
91 ip: self.ip.to_owned(),
97 /// Handle messages from chat server, we simply send it to peer websocket
98 /// These are room messages, IE sent to others in the room
99 impl Handler<WSMessage> for WSSession {
102 fn handle(&mut self, msg: WSMessage, ctx: &mut Self::Context) {
103 // println!("id: {} msg: {}", self.id, msg.0);
108 /// WebSocket message handler
109 impl StreamHandler<ws::Message, ws::ProtocolError> for WSSession {
110 fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
111 // println!("WEBSOCKET MESSAGE: {:?} from id: {}", msg, self.id);
113 ws::Message::Ping(msg) => {
114 self.hb = Instant::now();
117 ws::Message::Pong(_) => {
118 self.hb = Instant::now();
120 ws::Message::Text(text) => {
121 let m = text.trim().to_owned();
122 println!("WEBSOCKET MESSAGE: {:?} from id: {}", &m, self.id);
125 .send(StandardMessage {
130 .then(|res, _, ctx| {
132 Ok(res) => ctx.text(res),
141 ws::Message::Binary(_bin) => println!("Unexpected binary"),
142 ws::Message::Close(_) => {
151 /// helper method that sends ping to client every second.
153 /// also this method checks heartbeats from client
154 fn hb(&self, ctx: &mut ws::WebsocketContext<Self>) {
155 ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
156 // check client heartbeats
157 if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
158 // heartbeat timed out
159 println!("Websocket Client heartbeat failed, disconnecting!");
161 // notify chat server
162 act.cs_addr.do_send(Disconnect {
164 ip: act.ip.to_owned(),
170 // don't try to send a ping
180 let _ = env_logger::init();
181 let sys = actix::System::new("lemmy");
183 // Run the migrations from code
184 let conn = establish_connection();
185 embedded_migrations::run(&conn).unwrap();
187 // Start chat server actor in separate thread
188 let server = ChatServer::default().start();
189 // Create Http server with websocket support
190 HttpServer::new(move || {
192 .data(server.clone())
193 .service(web::resource("/api/v1/ws").to(chat_route))
194 // .service(web::resource("/api/v1/rest").route(web::post().to(||{})))
195 .service(web::resource("/").to(index))
197 .service(actix_files::Files::new("/static", front_end_dir()))
199 .bind("0.0.0.0:8536")
203 println!("Started http server: 0.0.0.0:8536");
207 fn index() -> Result<NamedFile, actix_web::error::Error> {
208 Ok(NamedFile::open(front_end_dir() + "/index.html")?)
211 fn front_end_dir() -> String {
212 env::var("LEMMY_FRONT_END_DIR").unwrap_or("../ui/dist".to_string())