]> Untitled Git - lemmy.git/blob - crates/websocket/src/handlers.rs
Fix API and clippy warnings
[lemmy.git] / crates / websocket / src / handlers.rs
1 use crate::{
2   chat_server::{ChatServer, SessionInfo},
3   messages::*,
4   OperationType,
5 };
6 use actix::{Actor, Context, Handler, ResponseFuture};
7 use lemmy_db_schema::naive_now;
8 use lemmy_utils::ConnectionId;
9 use log::{error, info};
10 use rand::Rng;
11 use serde::Serialize;
12
13 /// Make actor from `ChatServer`
14 impl Actor for ChatServer {
15   /// We are going to use simple Context, we just need ability to communicate
16   /// with other actors.
17   type Context = Context<Self>;
18 }
19
20 /// Handler for Connect message.
21 ///
22 /// Register new session and assign unique id to this session
23 impl Handler<Connect> for ChatServer {
24   type Result = ConnectionId;
25
26   fn handle(&mut self, msg: Connect, _ctx: &mut Context<Self>) -> Self::Result {
27     // register session with random id
28     let id = self.rng.gen::<usize>();
29     info!("{} joined", &msg.ip);
30
31     self.sessions.insert(
32       id,
33       SessionInfo {
34         addr: msg.addr,
35         ip: msg.ip,
36       },
37     );
38
39     id
40   }
41 }
42
43 /// Handler for Disconnect message.
44 impl Handler<Disconnect> for ChatServer {
45   type Result = ();
46
47   fn handle(&mut self, msg: Disconnect, _: &mut Context<Self>) {
48     // Remove connections from sessions and all 3 scopes
49     if self.sessions.remove(&msg.id).is_some() {
50       for sessions in self.user_rooms.values_mut() {
51         sessions.remove(&msg.id);
52       }
53
54       for sessions in self.post_rooms.values_mut() {
55         sessions.remove(&msg.id);
56       }
57
58       for sessions in self.community_rooms.values_mut() {
59         sessions.remove(&msg.id);
60       }
61     }
62   }
63 }
64
65 /// Handler for Message message.
66 impl Handler<StandardMessage> for ChatServer {
67   type Result = ResponseFuture<Result<String, std::convert::Infallible>>;
68
69   fn handle(&mut self, msg: StandardMessage, ctx: &mut Context<Self>) -> Self::Result {
70     let fut = self.parse_json_message(msg, ctx);
71     Box::pin(async move {
72       match fut.await {
73         Ok(m) => {
74           // info!("Message Sent: {}", m);
75           Ok(m)
76         }
77         Err(e) => {
78           error!("Error during message handling {}", e);
79           Ok(e.to_string())
80         }
81       }
82     })
83   }
84 }
85
86 impl<OP, Response> Handler<SendAllMessage<OP, Response>> for ChatServer
87 where
88   OP: OperationType + ToString,
89   Response: Serialize,
90 {
91   type Result = ();
92
93   fn handle(&mut self, msg: SendAllMessage<OP, Response>, _: &mut Context<Self>) {
94     self
95       .send_all_message(&msg.op, &msg.response, msg.websocket_id)
96       .ok();
97   }
98 }
99
100 impl<OP, Response> Handler<SendUserRoomMessage<OP, Response>> for ChatServer
101 where
102   OP: OperationType + ToString,
103   Response: Serialize,
104 {
105   type Result = ();
106
107   fn handle(&mut self, msg: SendUserRoomMessage<OP, Response>, _: &mut Context<Self>) {
108     self
109       .send_user_room_message(
110         &msg.op,
111         &msg.response,
112         msg.local_recipient_id,
113         msg.websocket_id,
114       )
115       .ok();
116   }
117 }
118
119 impl<OP, Response> Handler<SendCommunityRoomMessage<OP, Response>> for ChatServer
120 where
121   OP: OperationType + ToString,
122   Response: Serialize,
123 {
124   type Result = ();
125
126   fn handle(&mut self, msg: SendCommunityRoomMessage<OP, Response>, _: &mut Context<Self>) {
127     self
128       .send_community_room_message(&msg.op, &msg.response, msg.community_id, msg.websocket_id)
129       .ok();
130   }
131 }
132
133 impl<Response> Handler<SendModRoomMessage<Response>> for ChatServer
134 where
135   Response: Serialize,
136 {
137   type Result = ();
138
139   fn handle(&mut self, msg: SendModRoomMessage<Response>, _: &mut Context<Self>) {
140     self
141       .send_mod_room_message(&msg.op, &msg.response, msg.community_id, msg.websocket_id)
142       .ok();
143   }
144 }
145
146 impl<OP> Handler<SendPost<OP>> for ChatServer
147 where
148   OP: OperationType + ToString,
149 {
150   type Result = ();
151
152   fn handle(&mut self, msg: SendPost<OP>, _: &mut Context<Self>) {
153     self.send_post(&msg.op, &msg.post, msg.websocket_id).ok();
154   }
155 }
156
157 impl<OP> Handler<SendComment<OP>> for ChatServer
158 where
159   OP: OperationType + ToString,
160 {
161   type Result = ();
162
163   fn handle(&mut self, msg: SendComment<OP>, _: &mut Context<Self>) {
164     self
165       .send_comment(&msg.op, &msg.comment, msg.websocket_id)
166       .ok();
167   }
168 }
169
170 impl Handler<JoinUserRoom> for ChatServer {
171   type Result = ();
172
173   fn handle(&mut self, msg: JoinUserRoom, _: &mut Context<Self>) {
174     self.join_user_room(msg.local_user_id, msg.id).ok();
175   }
176 }
177
178 impl Handler<JoinCommunityRoom> for ChatServer {
179   type Result = ();
180
181   fn handle(&mut self, msg: JoinCommunityRoom, _: &mut Context<Self>) {
182     self.join_community_room(msg.community_id, msg.id).ok();
183   }
184 }
185
186 impl Handler<JoinModRoom> for ChatServer {
187   type Result = ();
188
189   fn handle(&mut self, msg: JoinModRoom, _: &mut Context<Self>) {
190     self.join_mod_room(msg.community_id, msg.id).ok();
191   }
192 }
193
194 impl Handler<JoinPostRoom> for ChatServer {
195   type Result = ();
196
197   fn handle(&mut self, msg: JoinPostRoom, _: &mut Context<Self>) {
198     self.join_post_room(msg.post_id, msg.id).ok();
199   }
200 }
201
202 impl Handler<GetUsersOnline> for ChatServer {
203   type Result = usize;
204
205   fn handle(&mut self, _msg: GetUsersOnline, _: &mut Context<Self>) -> Self::Result {
206     self.sessions.len()
207   }
208 }
209
210 impl Handler<GetPostUsersOnline> for ChatServer {
211   type Result = usize;
212
213   fn handle(&mut self, msg: GetPostUsersOnline, _: &mut Context<Self>) -> Self::Result {
214     if let Some(users) = self.post_rooms.get(&msg.post_id) {
215       users.len()
216     } else {
217       0
218     }
219   }
220 }
221
222 impl Handler<GetCommunityUsersOnline> for ChatServer {
223   type Result = usize;
224
225   fn handle(&mut self, msg: GetCommunityUsersOnline, _: &mut Context<Self>) -> Self::Result {
226     if let Some(users) = self.community_rooms.get(&msg.community_id) {
227       users.len()
228     } else {
229       0
230     }
231   }
232 }
233
234 impl Handler<CaptchaItem> for ChatServer {
235   type Result = ();
236
237   fn handle(&mut self, msg: CaptchaItem, _: &mut Context<Self>) {
238     self.captchas.push(msg);
239   }
240 }
241
242 impl Handler<CheckCaptcha> for ChatServer {
243   type Result = bool;
244
245   fn handle(&mut self, msg: CheckCaptcha, _: &mut Context<Self>) -> Self::Result {
246     // Remove all the ones that are past the expire time
247     self.captchas.retain(|x| x.expires.gt(&naive_now()));
248
249     let check = self
250       .captchas
251       .iter()
252       .any(|r| r.uuid == msg.uuid && r.answer == msg.answer);
253
254     // Remove this uuid so it can't be re-checked (Checks only work once)
255     self.captchas.retain(|x| x.uuid != msg.uuid);
256
257     check
258   }
259 }