1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
|
use std::collections::HashMap;
use axum::{response::Response, Router, routing::{post, patch, delete, get}, extract::{ws::Message, WebSocketUpgrade}};
use serde::Deserialize;
use tokio::sync::{Mutex, mpsc::{Sender, self}};
use crate::{
public::docs::{EndpointDocumentation, EndpointMethod},
types::{
extract::{AuthorizedUser, Check, CheckResult, Database, Json},
http::ResponseCode,
chat::{ChatRoom, ChatEvent}, user::User,
},
};
use std::collections::hash_map::Values;
use lazy_static::lazy_static;
lazy_static!(
static ref CONNECTIONS: Mutex<HashMap<u64, ConnectionPool>> = Mutex::new(HashMap::new());
);
struct ConnectionPool {
inner: HashMap<usize, Sender<ChatEvent>>,
index: usize
}
impl ConnectionPool {
fn new() -> Self {
Self {
inner: HashMap::new(),
index: 0
}
}
fn add(&mut self, send: Sender<ChatEvent>) -> usize {
let idx = self.index;
self.index += 1;
self.inner.insert(idx, send);
idx
}
fn del(&mut self, idx: &usize) {
self.inner.remove(idx);
}
fn values(&self) -> Values<'_, usize, Sender<ChatEvent>> {
self.inner.values()
}
}
async fn send_event(event: ChatEvent, room: &ChatRoom) {
for user in &room.users {
let lock = CONNECTIONS.lock().await;
let Some(connection) = lock.get(&user) else {
continue
};
for channel in connection.values() {
channel.send(event.clone()).await.ok();
}
}
}
pub const CHAT_LIST: EndpointDocumentation = EndpointDocumentation {
uri: "/api/chat/list",
method: EndpointMethod::Post,
description: "Returns the rooms you are in",
body: None,
responses: &[
(201, "Returns rooms in a list"),
(400, "Body does not match parameters"),
(401, "Unauthorized"),
(500, "Failed to retrieve rooms"),
],
cookie: Some("auth"),
};
async fn list (
AuthorizedUser(user): AuthorizedUser,
Database(db): Database
) -> Response {
let Ok(rooms) = ChatRoom::from_user_id(&db, user.user_id) else {
return ResponseCode::InternalServerError.text("Failed to retrieve rooms")
};
let Ok(json) = serde_json::to_string(&rooms) else {
return ResponseCode::InternalServerError.text("Failed to retrieve rooms")
};
ResponseCode::Success.json(&json)
}
pub const CHAT_CREATE: EndpointDocumentation = EndpointDocumentation {
uri: "/api/chat/create",
method: EndpointMethod::Post,
description: "Creates a new room",
body: Some(
r#"
{
"name" : "Funny memes"
}
"#,
),
responses: &[
(201, "Successfully created room"),
(400, "Body does not match parameters"),
(401, "Unauthorized"),
(500, "Failed to create room"),
],
cookie: Some("auth"),
};
#[derive(Deserialize)]
struct RoomCreateRequest {
name: String,
}
impl Check for RoomCreateRequest {
fn check(&self) -> CheckResult {
Self::assert_length(
&self.name,
1,
255,
"Room names must be between 1-255 characters long",
)?;
Ok(())
}
}
async fn create (
AuthorizedUser(user): AuthorizedUser,
Database(db): Database,
Json(body): Json<RoomCreateRequest>,
) -> Response {
let Ok(room) = ChatRoom::new(&db, vec![user.user_id], body.name) else {
return ResponseCode::InternalServerError.text("Failed to create room")
};
for user in &room.users {
send_event(ChatEvent::Add {
user_id: *user,
room_id: room.room_id
}, &room).await;
}
let Ok(json) = serde_json::to_string(&room) else {
return ResponseCode::InternalServerError.text("Failed to create room")
};
ResponseCode::Created.json(&json)
}
pub const CHAT_ADD: EndpointDocumentation = EndpointDocumentation {
uri: "/api/chat/add",
method: EndpointMethod::Patch,
description: "Adds a user to a room",
body: Some(
r#"
{
"room_id": 69,
"email" : "joebide@house.gov"
}
"#,
),
responses: &[
(201, "Successfully added user"),
(400, "Body does not match parameters"),
(401, "Unauthorized"),
(500, "Failed to add user"),
],
cookie: Some("auth"),
};
#[derive(Deserialize)]
struct AddUserRequest {
room_id: u64,
email: String,
}
impl Check for AddUserRequest {
fn check(&self) -> CheckResult {
Ok(())
}
}
async fn add (
AuthorizedUser(user): AuthorizedUser,
Database(db): Database,
Json(body): Json<AddUserRequest>,
) -> Response {
let Ok(to_add) = User::from_email(&db, &body.email) else {
return ResponseCode::BadRequest.text("User does not exist")
};
let Ok(room) = ChatRoom::from_user_and_room_id(&db, user.user_id, body.room_id) else {
return ResponseCode::BadRequest.text("Room doesnt exist or you are not in it")
};
let Ok(success) = room.add_user(&db, to_add.user_id) else {
return ResponseCode::InternalServerError.text("Failed to add user")
};
if !success {
return ResponseCode::BadRequest.text("User is already in the room")
}
send_event(ChatEvent::Add {
user_id: to_add.user_id,
room_id: room.room_id
}, &room).await;
ResponseCode::Success.text("Successfully added user")
}
pub const CHAT_LEAVE: EndpointDocumentation = EndpointDocumentation {
uri: "/api/chat/leave",
method: EndpointMethod::Delete,
description: "Leaves a room",
body: Some(
r#"
{
"room_id": 69
}
"#,
),
responses: &[
(201, "Successfully left room"),
(400, "Body does not match parameters"),
(401, "Unauthorized"),
(500, "Failed to leave a room"),
],
cookie: Some("auth"),
};
#[derive(Deserialize)]
struct LeaveRoomRequest {
room_id: u64,
}
impl Check for LeaveRoomRequest {
fn check(&self) -> CheckResult {
Ok(())
}
}
async fn leave (
AuthorizedUser(user): AuthorizedUser,
Database(db): Database,
Json(body): Json<LeaveRoomRequest>,
) -> Response {
let Ok(room) = ChatRoom::from_user_and_room_id(&db, user.user_id, body.room_id) else {
return ResponseCode::BadRequest.text("Room doesnt exist or you are not in it")
};
let Ok(success) = room.remove_user(&db, user.user_id) else {
return ResponseCode::InternalServerError.text("Failed to leave room")
};
if !success {
return ResponseCode::BadRequest.text("You are currently not in this room (how did this happen?)")
}
send_event(ChatEvent::Leave {
user_id: user.user_id,
room_id: room.room_id
}, &room).await;
ResponseCode::Success.text("Successfully left room")
}
pub const CHAT_SEND: EndpointDocumentation = EndpointDocumentation {
uri: "/api/chat/send",
method: EndpointMethod::Post,
description: "Send a message to a room",
body: Some(
r#"
{
"room_id": 420,
"content" : "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
"#,
),
responses: &[
(201, "Successfully sent message"),
(400, "Body does not match parameters"),
(401, "Unauthorized"),
(500, "Failed to send message"),
],
cookie: Some("auth"),
};
#[derive(Deserialize)]
struct SendMessageRequest {
room_id: u64,
content: String
}
impl Check for SendMessageRequest {
fn check(&self) -> CheckResult {
Self::assert_length(
&self.content,
1,
500,
"Messages must be between 1-500 length"
)?;
Ok(())
}
}
async fn send (
AuthorizedUser(user): AuthorizedUser,
Database(db): Database,
Json(body): Json<SendMessageRequest>,
) -> Response {
let Ok(room) = ChatRoom::from_user_and_room_id(&db, user.user_id, body.room_id) else {
return ResponseCode::BadRequest.text("Room doesnt exist or you are not in it")
};
let Ok(msg) = room.send_message(&db, user.user_id, body.content) else {
return ResponseCode::InternalServerError.text("Failed to send message")
};
send_event(ChatEvent::Message {
user_id: msg.user_id,
room_id: msg.room_id,
message_id: msg.message_id,
content: msg.content,
date: msg.date
}, &room).await;
ResponseCode::Created.text("Successfully sent message")
}
pub const CHAT_LOAD: EndpointDocumentation = EndpointDocumentation {
uri: "/api/chat/load",
method: EndpointMethod::Post,
description: "Get a page of historic room messages starting before given message id",
body: Some(
r#"
{
"room_id": 69,
"newest_msg": 400,
"page": 3
}
"#,
),
responses: &[
(201, "Successfully sent message"),
(400, "Body does not match parameters"),
(401, "Unauthorized"),
(500, "Failed to send message"),
],
cookie: Some("auth"),
};
#[derive(Deserialize)]
struct LoadMessagesRequest {
room_id: u64,
newest_msg: u64,
page: u64
}
impl Check for LoadMessagesRequest {
fn check(&self) -> CheckResult {
Ok(())
}
}
async fn load (
AuthorizedUser(user): AuthorizedUser,
Database(db): Database,
Json(body): Json<LoadMessagesRequest>,
) -> Response {
let Ok(room) = ChatRoom::from_user_and_room_id(&db, user.user_id, body.room_id) else {
return ResponseCode::BadRequest.text("Room doesnt exist or you are not in it")
};
let Ok(msgs) = room.load_old_chat_messages(&db, body.newest_msg, body.page) else {
return ResponseCode::InternalServerError.text("Failed to load messages")
};
let Ok(json) = serde_json::to_string(&msgs) else {
return ResponseCode::InternalServerError.text("Failed to load messages")
};
ResponseCode::Created.json(&json)
}
pub const CHAT_TYPING: EndpointDocumentation = EndpointDocumentation {
uri: "/api/chat/typing",
method: EndpointMethod::Post,
description: "Set if your typing in a given room",
body: Some(
r#"
{
"room_id": 69,
}
"#,
),
responses: &[
(201, "Successfully sent typing indicator"),
(400, "Body does not match parameters"),
(401, "Unauthorized"),
(500, "Failed to send typing indicator"),
],
cookie: Some("auth"),
};
#[derive(Deserialize)]
struct TypingRequest {
room_id: u64,
}
impl Check for TypingRequest {
fn check(&self) -> CheckResult {
Ok(())
}
}
async fn typing (
AuthorizedUser(user): AuthorizedUser,
Database(db): Database,
Json(body): Json<TypingRequest>,
) -> Response {
let Ok(room) = ChatRoom::from_user_and_room_id(&db, user.user_id, body.room_id) else {
return ResponseCode::BadRequest.text("Room doesnt exist or you are not in it")
};
send_event(ChatEvent::Typing {
user_id: user.user_id,
room_id: room.room_id,
}, &room).await;
ResponseCode::Success.text("Successfully sent typing indicator")
}
pub const CHAT_CONNECT: EndpointDocumentation = EndpointDocumentation {
uri: "/api/chat/connect",
method: EndpointMethod::Get,
description: "Start a websocket connection for chat events",
body: None,
responses: &[],
cookie: Some("auth"),
};
async fn connect (
AuthorizedUser(user): AuthorizedUser,
ws: WebSocketUpgrade
) -> Response {
ws.on_upgrade(|mut ws| async move {
let user = user;
let (send, mut recv) = mpsc::channel::<ChatEvent>(20);
let id: usize;
{
let mut lock = CONNECTIONS.lock().await;
match lock.get_mut(&user.user_id) {
Some(pool) => {
id = pool.add(send);
},
None => {
let mut pool = ConnectionPool::new();
id = pool.add(send);
lock.insert(user.user_id, pool);
}
};
}
loop {
tokio::select! {
m = ws.recv() => {
let Some(Ok(_)) = m else {
break;
};
}
s = recv.recv() => {
let Some(msg) = s else {
break;
};
if let Ok(string) = serde_json::to_string(&msg) {
ws.send(Message::Text(string)).await.ok();
}
}
}
}
let mut lock = CONNECTIONS.lock().await;
if let Some(conn) = lock.get_mut(&user.user_id) {
conn.del(&id);
};
})
}
pub fn router() -> Router {
Router::new()
.route("/create", post(create))
.route("/list", post(list))
.route("/add", patch(add))
.route("/leave", delete(leave))
.route("/send", post(send))
.route("/load", post(load))
.route("/typing", post(typing))
.route("/connect", get(connect))
}
|