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();
73 addr: addr.recipient(),
74 ip: self.ip.to_owned(),
77 .then(|res, act, ctx| {
79 Ok(res) => act.id = res,
80 // something is wrong with chat server
88 fn stopping(&mut self, _ctx: &mut Self::Context) -> Running {
90 self.cs_addr.do_send(Disconnect {
92 ip: self.ip.to_owned(),
98 /// Handle messages from chat server, we simply send it to peer websocket
99 /// These are room messages, IE sent to others in the room
100 impl Handler<WSMessage> for WSSession {
103 fn handle(&mut self, msg: WSMessage, ctx: &mut Self::Context) {
104 // println!("id: {} msg: {}", self.id, msg.0);
109 /// WebSocket message handler
110 impl StreamHandler<ws::Message, ws::ProtocolError> for WSSession {
111 fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
112 // println!("WEBSOCKET MESSAGE: {:?} from id: {}", msg, self.id);
114 ws::Message::Ping(msg) => {
115 self.hb = Instant::now();
118 ws::Message::Pong(_) => {
119 self.hb = Instant::now();
121 ws::Message::Text(text) => {
122 let m = text.trim().to_owned();
123 println!("WEBSOCKET MESSAGE: {:?} from id: {}", &m, self.id);
127 .send(StandardMessage {
132 .then(|res, _, ctx| {
134 Ok(res) => ctx.text(res),
143 ws::Message::Binary(_bin) => println!("Unexpected binary"),
144 ws::Message::Close(_) => {
153 /// helper method that sends ping to client every second.
155 /// also this method checks heartbeats from client
156 fn hb(&self, ctx: &mut ws::WebsocketContext<Self>) {
157 ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
158 // check client heartbeats
159 if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
160 // heartbeat timed out
161 println!("Websocket Client heartbeat failed, disconnecting!");
163 // notify chat server
164 act.cs_addr.do_send(Disconnect {
166 ip: act.ip.to_owned(),
172 // don't try to send a ping
182 let _ = env_logger::init();
183 let sys = actix::System::new("lemmy");
185 // Run the migrations from code
186 let conn = establish_connection();
187 embedded_migrations::run(&conn).unwrap();
189 // Start chat server actor in separate thread
190 let server = ChatServer::default().start();
191 // Create Http server with websocket support
192 HttpServer::new(move || {
194 .data(server.clone())
195 .service(web::resource("/api/v1/ws").to(chat_route))
196 // .service(web::resource("/api/v1/rest").route(web::post().to(||{})))
197 .service(web::resource("/").to(index))
199 .service(actix_files::Files::new("/static", front_end_dir()))
201 .bind("0.0.0.0:8536")
205 println!("Started http server: 0.0.0.0:8536");
209 fn index() -> Result<NamedFile, actix_web::error::Error> {
210 Ok(NamedFile::open(front_end_dir() + "/index.html")?)
213 fn front_end_dir() -> String {
214 env::var("LEMMY_FRONT_END_DIR").unwrap_or("../ui/dist".to_string())