]> Untitled Git - lemmy.git/blob - server/src/websocket/server.rs
Merge pull request #6 from dessalines/dev
[lemmy.git] / server / src / websocket / server.rs
1 //! `ChatServer` is an actor. It maintains list of connection client session.
2 //! And manages available rooms. Peers send messages to other peers in same
3 //! room through `ChatServer`.
4
5 use actix::prelude::*;
6 use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
7 use diesel::PgConnection;
8 use failure::Error;
9 use rand::{rngs::ThreadRng, Rng};
10 use serde::{Deserialize, Serialize};
11 use serde_json::Value;
12 use std::collections::{HashMap, HashSet};
13 use std::str::FromStr;
14 use std::time::SystemTime;
15
16 use crate::api::comment::*;
17 use crate::api::community::*;
18 use crate::api::post::*;
19 use crate::api::site::*;
20 use crate::api::user::*;
21 use crate::api::*;
22 use crate::websocket::UserOperation;
23 use crate::Settings;
24
25 /// Chat server sends this messages to session
26 #[derive(Message)]
27 #[rtype(result = "()")]
28 pub struct WSMessage(pub String);
29
30 /// Message for chat server communications
31
32 /// New chat session is created
33 #[derive(Message)]
34 #[rtype(usize)]
35 pub struct Connect {
36   pub addr: Recipient<WSMessage>,
37   pub ip: String,
38 }
39
40 /// Session is disconnected
41 #[derive(Message)]
42 #[rtype(result = "()")]
43 pub struct Disconnect {
44   pub id: usize,
45   pub ip: String,
46 }
47
48 // TODO this is unused rn
49 /// Send message to specific room
50 #[derive(Message)]
51 #[rtype(result = "()")]
52 pub struct ClientMessage {
53   /// Id of the client session
54   pub id: usize,
55   /// Peer message
56   pub msg: String,
57   /// Room name
58   pub room: String,
59 }
60
61 #[derive(Serialize, Deserialize, Message)]
62 #[rtype(String)]
63 pub struct StandardMessage {
64   /// Id of the client session
65   pub id: usize,
66   /// Peer message
67   pub msg: String,
68 }
69
70 #[derive(Debug)]
71 pub struct RateLimitBucket {
72   last_checked: SystemTime,
73   allowance: f64,
74 }
75
76 pub struct SessionInfo {
77   pub addr: Recipient<WSMessage>,
78   pub ip: String,
79 }
80
81 /// `ChatServer` manages chat rooms and responsible for coordinating chat
82 /// session. implementation is super primitive
83 pub struct ChatServer {
84   sessions: HashMap<usize, SessionInfo>, // A map from generated random ID to session addr
85   rate_limits: HashMap<String, RateLimitBucket>,
86   rooms: HashMap<i32, HashSet<usize>>, // A map from room / post name to set of connectionIDs
87   rng: ThreadRng,
88   db: Pool<ConnectionManager<PgConnection>>,
89 }
90
91 impl ChatServer {
92   pub fn startup(db: Pool<ConnectionManager<PgConnection>>) -> ChatServer {
93     // default room
94     let rooms = HashMap::new();
95
96     ChatServer {
97       sessions: HashMap::new(),
98       rate_limits: HashMap::new(),
99       rooms,
100       rng: rand::thread_rng(),
101       db,
102     }
103   }
104
105   /// Send message to all users in the room
106   fn send_room_message(&self, room: i32, message: &str, skip_id: usize) {
107     if let Some(sessions) = self.rooms.get(&room) {
108       for id in sessions {
109         if *id != skip_id {
110           if let Some(info) = self.sessions.get(id) {
111             let _ = info.addr.do_send(WSMessage(message.to_owned()));
112           }
113         }
114       }
115     }
116   }
117
118   fn join_room(&mut self, room_id: i32, id: usize) {
119     // remove session from all rooms
120     for sessions in self.rooms.values_mut() {
121       sessions.remove(&id);
122     }
123
124     // If the room doesn't exist yet
125     if self.rooms.get_mut(&room_id).is_none() {
126       self.rooms.insert(room_id, HashSet::new());
127     }
128
129     self.rooms.get_mut(&room_id).unwrap().insert(id);
130   }
131
132   fn send_community_message(
133     &self,
134     community_id: i32,
135     message: &str,
136     skip_id: usize,
137   ) -> Result<(), Error> {
138     use crate::db::post_view::*;
139     use crate::db::*;
140
141     let conn = self.db.get()?;
142
143     let posts = PostQueryBuilder::create(&conn)
144       .listing_type(ListingType::Community)
145       .sort(&SortType::New)
146       .for_community_id(community_id)
147       .limit(9999)
148       .list()?;
149
150     for post in posts {
151       self.send_room_message(post.id, message, skip_id);
152     }
153
154     Ok(())
155   }
156
157   fn check_rate_limit_register(&mut self, id: usize) -> Result<(), Error> {
158     self.check_rate_limit_full(
159       id,
160       Settings::get().rate_limit.register,
161       Settings::get().rate_limit.register_per_second,
162     )
163   }
164
165   fn check_rate_limit_post(&mut self, id: usize) -> Result<(), Error> {
166     self.check_rate_limit_full(
167       id,
168       Settings::get().rate_limit.post,
169       Settings::get().rate_limit.post_per_second,
170     )
171   }
172
173   fn check_rate_limit_message(&mut self, id: usize) -> Result<(), Error> {
174     self.check_rate_limit_full(
175       id,
176       Settings::get().rate_limit.message,
177       Settings::get().rate_limit.message_per_second,
178     )
179   }
180
181   #[allow(clippy::float_cmp)]
182   fn check_rate_limit_full(&mut self, id: usize, rate: i32, per: i32) -> Result<(), Error> {
183     if let Some(info) = self.sessions.get(&id) {
184       if let Some(rate_limit) = self.rate_limits.get_mut(&info.ip) {
185         // The initial value
186         if rate_limit.allowance == -2f64 {
187           rate_limit.allowance = rate as f64;
188         };
189
190         let current = SystemTime::now();
191         let time_passed = current.duration_since(rate_limit.last_checked)?.as_secs() as f64;
192         rate_limit.last_checked = current;
193         rate_limit.allowance += time_passed * (rate as f64 / per as f64);
194         if rate_limit.allowance > rate as f64 {
195           rate_limit.allowance = rate as f64;
196         }
197
198         if rate_limit.allowance < 1.0 {
199           println!(
200             "Rate limited IP: {}, time_passed: {}, allowance: {}",
201             &info.ip, time_passed, rate_limit.allowance
202           );
203           Err(
204             APIError {
205               message: format!("Too many requests. {} per {} seconds", rate, per),
206             }
207             .into(),
208           )
209         } else {
210           rate_limit.allowance -= 1.0;
211           Ok(())
212         }
213       } else {
214         Ok(())
215       }
216     } else {
217       Ok(())
218     }
219   }
220 }
221
222 /// Make actor from `ChatServer`
223 impl Actor for ChatServer {
224   /// We are going to use simple Context, we just need ability to communicate
225   /// with other actors.
226   type Context = Context<Self>;
227 }
228
229 /// Handler for Connect message.
230 ///
231 /// Register new session and assign unique id to this session
232 impl Handler<Connect> for ChatServer {
233   type Result = usize;
234
235   fn handle(&mut self, msg: Connect, _ctx: &mut Context<Self>) -> Self::Result {
236     // notify all users in same room
237     // self.send_room_message(&"Main".to_owned(), "Someone joined", 0);
238
239     // register session with random id
240     let id = self.rng.gen::<usize>();
241     println!("{} joined", &msg.ip);
242
243     self.sessions.insert(
244       id,
245       SessionInfo {
246         addr: msg.addr,
247         ip: msg.ip.to_owned(),
248       },
249     );
250
251     if self.rate_limits.get(&msg.ip).is_none() {
252       self.rate_limits.insert(
253         msg.ip,
254         RateLimitBucket {
255           last_checked: SystemTime::now(),
256           allowance: -2f64,
257         },
258       );
259     }
260
261     id
262   }
263 }
264
265 /// Handler for Disconnect message.
266 impl Handler<Disconnect> for ChatServer {
267   type Result = ();
268
269   fn handle(&mut self, msg: Disconnect, _: &mut Context<Self>) {
270     // let mut rooms: Vec<i32> = Vec::new();
271
272     // remove address
273     if self.sessions.remove(&msg.id).is_some() {
274       // remove session from all rooms
275       for sessions in self.rooms.values_mut() {
276         if sessions.remove(&msg.id) {
277           // rooms.push(*id);
278         }
279       }
280     }
281   }
282 }
283
284 /// Handler for Message message.
285 impl Handler<StandardMessage> for ChatServer {
286   type Result = MessageResult<StandardMessage>;
287
288   fn handle(&mut self, msg: StandardMessage, _: &mut Context<Self>) -> Self::Result {
289     let msg_out = match parse_json_message(self, msg) {
290       Ok(m) => m,
291       Err(e) => e.to_string(),
292     };
293
294     println!("Message Sent: {}", msg_out);
295     MessageResult(msg_out)
296   }
297 }
298
299 #[derive(Serialize)]
300 struct WebsocketResponse<T> {
301   op: String,
302   data: T,
303 }
304
305 fn to_json_string<T>(op: &UserOperation, data: T) -> Result<String, Error>
306 where
307   T: Serialize,
308 {
309   let response = WebsocketResponse {
310     op: op.to_string(),
311     data,
312   };
313   Ok(serde_json::to_string(&response)?)
314 }
315
316 fn do_user_operation<'a, Data, Response>(
317   op: UserOperation,
318   data: &str,
319   conn: &PooledConnection<ConnectionManager<PgConnection>>,
320 ) -> Result<String, Error>
321 where
322   for<'de> Data: Deserialize<'de> + 'a,
323   Response: Serialize,
324   Oper<Data>: Perform<Response>,
325 {
326   let parsed_data: Data = serde_json::from_str(data)?;
327   let res = Oper::new(parsed_data).perform(&conn)?;
328   to_json_string(&op, &res)
329 }
330
331 fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result<String, Error> {
332   let json: Value = serde_json::from_str(&msg.msg)?;
333   let data = &json["data"].to_string();
334   let op = &json["op"].as_str().ok_or(APIError {
335     message: "Unknown op type".to_string(),
336   })?;
337
338   let conn = chat.db.get()?;
339
340   let user_operation: UserOperation = UserOperation::from_str(&op)?;
341
342   // TODO: none of the chat messages are going to work if stuff is submitted via http api,
343   //       need to move that handling elsewhere
344   match user_operation {
345     UserOperation::Login => do_user_operation::<Login, LoginResponse>(user_operation, data, &conn),
346     UserOperation::Register => {
347       chat.check_rate_limit_register(msg.id)?;
348       do_user_operation::<Register, LoginResponse>(user_operation, data, &conn)
349     }
350     UserOperation::GetUserDetails => {
351       do_user_operation::<GetUserDetails, GetUserDetailsResponse>(user_operation, data, &conn)
352     }
353     UserOperation::SaveUserSettings => {
354       do_user_operation::<SaveUserSettings, LoginResponse>(user_operation, data, &conn)
355     }
356     UserOperation::AddAdmin => {
357       do_user_operation::<AddAdmin, AddAdminResponse>(user_operation, data, &conn)
358     }
359     UserOperation::BanUser => {
360       do_user_operation::<BanUser, BanUserResponse>(user_operation, data, &conn)
361     }
362     UserOperation::GetReplies => {
363       do_user_operation::<GetReplies, GetRepliesResponse>(user_operation, data, &conn)
364     }
365     UserOperation::GetUserMentions => {
366       do_user_operation::<GetUserMentions, GetUserMentionsResponse>(user_operation, data, &conn)
367     }
368     UserOperation::EditUserMention => {
369       do_user_operation::<EditUserMention, UserMentionResponse>(user_operation, data, &conn)
370     }
371     UserOperation::MarkAllAsRead => {
372       do_user_operation::<MarkAllAsRead, GetRepliesResponse>(user_operation, data, &conn)
373     }
374     UserOperation::GetCommunity => {
375       do_user_operation::<GetCommunity, GetCommunityResponse>(user_operation, data, &conn)
376     }
377     UserOperation::ListCommunities => {
378       do_user_operation::<ListCommunities, ListCommunitiesResponse>(user_operation, data, &conn)
379     }
380     UserOperation::CreateCommunity => {
381       chat.check_rate_limit_register(msg.id)?;
382       do_user_operation::<CreateCommunity, CommunityResponse>(user_operation, data, &conn)
383     }
384     UserOperation::EditCommunity => {
385       let edit_community: EditCommunity = serde_json::from_str(data)?;
386       let res = Oper::new(edit_community).perform(&conn)?;
387       let mut community_sent: CommunityResponse = res.clone();
388       community_sent.community.user_id = None;
389       community_sent.community.subscribed = None;
390       let community_sent_str = to_json_string(&user_operation, &community_sent)?;
391       chat.send_community_message(community_sent.community.id, &community_sent_str, msg.id)?;
392       to_json_string(&user_operation, &res)
393     }
394     UserOperation::FollowCommunity => {
395       do_user_operation::<FollowCommunity, CommunityResponse>(user_operation, data, &conn)
396     }
397     UserOperation::GetFollowedCommunities => do_user_operation::<
398       GetFollowedCommunities,
399       GetFollowedCommunitiesResponse,
400     >(user_operation, data, &conn),
401     UserOperation::BanFromCommunity => {
402       let ban_from_community: BanFromCommunity = serde_json::from_str(data)?;
403       let community_id = ban_from_community.community_id;
404       let res = Oper::new(ban_from_community).perform(&conn)?;
405       let res_str = to_json_string(&user_operation, &res)?;
406       chat.send_community_message(community_id, &res_str, msg.id)?;
407       Ok(res_str)
408     }
409     UserOperation::AddModToCommunity => {
410       let mod_add_to_community: AddModToCommunity = serde_json::from_str(data)?;
411       let community_id = mod_add_to_community.community_id;
412       let res = Oper::new(mod_add_to_community).perform(&conn)?;
413       let res_str = to_json_string(&user_operation, &res)?;
414       chat.send_community_message(community_id, &res_str, msg.id)?;
415       Ok(res_str)
416     }
417     UserOperation::ListCategories => {
418       do_user_operation::<ListCategories, ListCategoriesResponse>(user_operation, data, &conn)
419     }
420     UserOperation::CreatePost => {
421       chat.check_rate_limit_post(msg.id)?;
422       do_user_operation::<CreatePost, PostResponse>(user_operation, data, &conn)
423     }
424     UserOperation::GetPost => {
425       let get_post: GetPost = serde_json::from_str(data)?;
426       chat.join_room(get_post.id, msg.id);
427       let res = Oper::new(get_post).perform(&conn)?;
428       to_json_string(&user_operation, &res)
429     }
430     UserOperation::GetPosts => {
431       do_user_operation::<GetPosts, GetPostsResponse>(user_operation, data, &conn)
432     }
433     UserOperation::CreatePostLike => {
434       chat.check_rate_limit_message(msg.id)?;
435       do_user_operation::<CreatePostLike, CreatePostLikeResponse>(user_operation, data, &conn)
436     }
437     UserOperation::EditPost => {
438       let edit_post: EditPost = serde_json::from_str(data)?;
439       let res = Oper::new(edit_post).perform(&conn)?;
440       let mut post_sent = res.clone();
441       post_sent.post.my_vote = None;
442       let post_sent_str = to_json_string(&user_operation, &post_sent)?;
443       chat.send_room_message(post_sent.post.id, &post_sent_str, msg.id);
444       to_json_string(&user_operation, &res)
445     }
446     UserOperation::SavePost => {
447       do_user_operation::<SavePost, PostResponse>(user_operation, data, &conn)
448     }
449     UserOperation::CreateComment => {
450       chat.check_rate_limit_message(msg.id)?;
451       let create_comment: CreateComment = serde_json::from_str(data)?;
452       let post_id = create_comment.post_id;
453       let res = Oper::new(create_comment).perform(&conn)?;
454       let mut comment_sent = res.clone();
455       comment_sent.comment.my_vote = None;
456       comment_sent.comment.user_id = None;
457       let comment_sent_str = to_json_string(&user_operation, &comment_sent)?;
458       chat.send_room_message(post_id, &comment_sent_str, msg.id);
459       to_json_string(&user_operation, &res)
460     }
461     UserOperation::EditComment => {
462       let edit_comment: EditComment = serde_json::from_str(data)?;
463       let post_id = edit_comment.post_id;
464       let res = Oper::new(edit_comment).perform(&conn)?;
465       let mut comment_sent = res.clone();
466       comment_sent.comment.my_vote = None;
467       comment_sent.comment.user_id = None;
468       let comment_sent_str = to_json_string(&user_operation, &comment_sent)?;
469       chat.send_room_message(post_id, &comment_sent_str, msg.id);
470       to_json_string(&user_operation, &res)
471     }
472     UserOperation::SaveComment => {
473       do_user_operation::<SaveComment, CommentResponse>(user_operation, data, &conn)
474     }
475     UserOperation::CreateCommentLike => {
476       chat.check_rate_limit_message(msg.id)?;
477       let create_comment_like: CreateCommentLike = serde_json::from_str(data)?;
478       let post_id = create_comment_like.post_id;
479       let res = Oper::new(create_comment_like).perform(&conn)?;
480       let mut comment_sent = res.clone();
481       comment_sent.comment.my_vote = None;
482       comment_sent.comment.user_id = None;
483       let comment_sent_str = to_json_string(&user_operation, &comment_sent)?;
484       chat.send_room_message(post_id, &comment_sent_str, msg.id);
485       to_json_string(&user_operation, &res)
486     }
487     UserOperation::GetModlog => {
488       do_user_operation::<GetModlog, GetModlogResponse>(user_operation, data, &conn)
489     }
490     UserOperation::CreateSite => {
491       do_user_operation::<CreateSite, SiteResponse>(user_operation, data, &conn)
492     }
493     UserOperation::EditSite => {
494       do_user_operation::<EditSite, SiteResponse>(user_operation, data, &conn)
495     }
496     UserOperation::GetSite => {
497       let online: usize = chat.sessions.len();
498       let get_site: GetSite = serde_json::from_str(data)?;
499       let mut res = Oper::new(get_site).perform(&conn)?;
500       res.online = online;
501       to_json_string(&user_operation, &res)
502     }
503     UserOperation::Search => {
504       do_user_operation::<Search, SearchResponse>(user_operation, data, &conn)
505     }
506     UserOperation::TransferCommunity => {
507       do_user_operation::<TransferCommunity, GetCommunityResponse>(user_operation, data, &conn)
508     }
509     UserOperation::TransferSite => {
510       do_user_operation::<TransferSite, GetSiteResponse>(user_operation, data, &conn)
511     }
512     UserOperation::DeleteAccount => {
513       do_user_operation::<DeleteAccount, LoginResponse>(user_operation, data, &conn)
514     }
515     UserOperation::PasswordReset => {
516       do_user_operation::<PasswordReset, PasswordResetResponse>(user_operation, data, &conn)
517     }
518     UserOperation::PasswordChange => {
519       do_user_operation::<PasswordChange, LoginResponse>(user_operation, data, &conn)
520     }
521     UserOperation::CreatePrivateMessage => {
522       chat.check_rate_limit_message(msg.id)?;
523       do_user_operation::<CreatePrivateMessage, PrivateMessageResponse>(user_operation, data, &conn)
524     }
525     UserOperation::EditPrivateMessage => {
526       do_user_operation::<EditPrivateMessage, PrivateMessageResponse>(user_operation, data, &conn)
527     }
528     UserOperation::GetPrivateMessages => {
529       do_user_operation::<GetPrivateMessages, PrivateMessagesResponse>(user_operation, data, &conn)
530     }
531   }
532 }