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;
11 use lemmy_server::nodeinfo;
13 use lemmy_server::feeds;
14 >>>>>>> Implement RSS feeds (fixes #118)
15 use lemmy_server::websocket::server::*;
17 use std::time::{Duration, Instant};
21 /// How often heartbeat pings are sent
22 const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
23 /// How long before lack of client response causes a timeout
24 const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
26 /// Entry point for our route
30 chat_server: web::Data<Addr<ChatServer>>,
31 ) -> Result<HttpResponse, Error> {
34 cs_addr: chat_server.get_ref().to_owned(),
40 .unwrap_or("127.0.0.1:12345")
43 .unwrap_or("127.0.0.1")
52 cs_addr: Addr<ChatServer>,
56 /// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT),
57 /// otherwise we drop connection.
61 impl Actor for WSSession {
62 type Context = ws::WebsocketContext<Self>;
64 /// Method is called on actor start.
65 /// We register ws session with ChatServer
66 fn started(&mut self, ctx: &mut Self::Context) {
67 // we'll start heartbeat process on session start.
70 // register self in chat server. `AsyncContext::wait` register
71 // future within context, but context waits until this future resolves
72 // before processing any other events.
73 // across all routes within application
74 let addr = ctx.address();
78 addr: addr.recipient(),
79 ip: self.ip.to_owned(),
82 .then(|res, act, ctx| {
84 Ok(res) => act.id = res,
85 // something is wrong with chat server
93 fn stopping(&mut self, _ctx: &mut Self::Context) -> Running {
95 self.cs_addr.do_send(Disconnect {
97 ip: self.ip.to_owned(),
103 /// Handle messages from chat server, we simply send it to peer websocket
104 /// These are room messages, IE sent to others in the room
105 impl Handler<WSMessage> for WSSession {
108 fn handle(&mut self, msg: WSMessage, ctx: &mut Self::Context) {
109 // println!("id: {} msg: {}", self.id, msg.0);
114 /// WebSocket message handler
115 impl StreamHandler<ws::Message, ws::ProtocolError> for WSSession {
116 fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
117 // println!("WEBSOCKET MESSAGE: {:?} from id: {}", msg, self.id);
119 ws::Message::Ping(msg) => {
120 self.hb = Instant::now();
123 ws::Message::Pong(_) => {
124 self.hb = Instant::now();
126 ws::Message::Text(text) => {
127 let m = text.trim().to_owned();
128 println!("WEBSOCKET MESSAGE: {:?} from id: {}", &m, self.id);
132 .send(StandardMessage {
137 .then(|res, _, ctx| {
139 Ok(res) => ctx.text(res),
148 ws::Message::Binary(_bin) => println!("Unexpected binary"),
149 ws::Message::Close(_) => {
158 /// helper method that sends ping to client every second.
160 /// also this method checks heartbeats from client
161 fn hb(&self, ctx: &mut ws::WebsocketContext<Self>) {
162 ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
163 // check client heartbeats
164 if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
165 // heartbeat timed out
166 println!("Websocket Client heartbeat failed, disconnecting!");
168 // notify chat server
169 act.cs_addr.do_send(Disconnect {
171 ip: act.ip.to_owned(),
177 // don't try to send a ping
187 let _ = env_logger::init();
188 let sys = actix::System::new("lemmy");
190 // Run the migrations from code
191 let conn = establish_connection();
192 embedded_migrations::run(&conn).unwrap();
194 // Start chat server actor in separate thread
195 let server = ChatServer::default().start();
196 // Create Http server with websocket support
198 HttpServer::new(move || {
200 .data(server.clone())
201 .service(web::resource("/api/v1/ws").to(chat_route))
202 // .service(web::resource("/api/v1/rest").route(web::post().to(||{})))
203 .service(web::resource("/").to(index))
204 .route("/nodeinfo/2.0.json", web::get().to(nodeinfo::node_info))
206 "/.well-known/nodeinfo",
207 web::get().to(nodeinfo::node_info_well_known),
209 .route("/feeds/{type}/{name}.xml", web::get().to(feeds::get_feed))
210 // TODO: probably need a different function for this (or just handle all of /feeds?
211 // TODO: would be nice to use ListingType, but that doesnt include user
212 .route("/feeds/all.xml", web::get().to(feeds::get_feed))
214 .service(actix_files::Files::new("/static", front_end_dir()))
216 .bind("0.0.0.0:8536")
220 println!("Started http server: 0.0.0.0:8536");
224 fn index() -> Result<NamedFile, actix_web::error::Error> {
225 Ok(NamedFile::open(front_end_dir() + "/index.html")?)
228 fn front_end_dir() -> String {
229 env::var("LEMMY_FRONT_END_DIR").unwrap_or("../ui/dist".to_string())