This repository has been archived by the owner on Jan 16, 2023. It is now read-only.
/
messagingHandler.go
423 lines (361 loc) · 12.3 KB
/
messagingHandler.go
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
package routes
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"illusionman1212/twatter-go/db"
"illusionman1212/twatter-go/logger"
"illusionman1212/twatter-go/models"
"illusionman1212/twatter-go/utils"
"net/http"
"os"
"sort"
"strconv"
"github.com/gorilla/mux"
"github.com/jackc/pgtype"
"github.com/jackc/pgx/v4"
)
func StartConversation(w http.ResponseWriter, req *http.Request) {
body := &models.ConversationInitPayload{}
err := json.NewDecoder(req.Body).Decode(&body)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while decoding request body: ", err)
return
}
sessionUser, err := utils.ValidateSession(req, w)
if err != nil {
logger.Error(err)
return
}
if sessionUser.ID != fmt.Sprintf("%v", body.SenderId) {
utils.UnauthorizedWithJSON(w, `{
"message": "Unauthorized user, please log in",
"status": 401,
"success": false
}`)
logger.Info("Mismatching cookie user id and senderId")
return
}
if body.ReceiverId == body.SenderId {
utils.BadRequestWithJSON(w, `{
"message": "Invalid or incomplete request",
"status": 400,
"success": false
}`)
logger.Infof("Attempt to start conversation with self. ID: %v", body.ReceiverId)
return
}
// checking if the conversation already exists (it exists if initiated by the other party but no messages were sent)
checkQuery := `SELECT id, participants FROM conversations WHERE members = $1;`
existingConvoId := uint64(0)
existingParticipants := make([]uint64, 0)
receiverId, err := strconv.Atoi(body.ReceiverId)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while converting string to int: %v", err)
return
}
senderId, err := strconv.Atoi(body.SenderId)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while converting string to int: %v", err)
return
}
membersToCheck := []uint64{uint64(receiverId), uint64(senderId)}
// if the sorted members slice matches an existing sorted array in the DB then a conversation already exists. otherwise create a new one
sort.Slice(membersToCheck, func(i, j int) bool { return membersToCheck[i] < membersToCheck[j] })
err = db.DBPool.QueryRow(context.Background(), checkQuery, membersToCheck).Scan(&existingConvoId, &existingParticipants)
if err != nil {
if err != pgx.ErrNoRows {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while fetching conversation: %v", err)
return
}
}
if existingConvoId != 0 {
// check if the sender isn't in the participants and add them
if !utils.Contains(existingParticipants, body.SenderId) {
updateQuery := `UPDATE conversations SET participants = $1 WHERE id = $2`
newParticipants := append(existingParticipants, uint64(senderId))
sort.Slice(newParticipants, func(i, j int) bool { return newParticipants[i] < newParticipants[j] })
_, err = db.DBPool.Exec(context.Background(), updateQuery, newParticipants, existingConvoId)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while updating existing conversation: %v", err)
return
}
}
utils.OkWithJSON(w, fmt.Sprintf(`{
"message": "Conversation found",
"status": 200,
"success": true,
"conversationId": "%v"
}`, existingConvoId))
return
}
convoId, err := db.Snowflake.NextID()
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while generating a new id: ", err)
return
}
members := []uint64{uint64(receiverId), uint64(senderId)}
participants := []uint64{uint64(senderId)}
// always sort the members array so lookups in the DB are faster and we're able to easily compare
sort.Slice(members, func(i, j int) bool { return members[i] < members[j] })
insertQuery := `INSERT INTO conversations(id, members, participants)
VALUES($1, $2, $3)`
_, err = db.DBPool.Exec(context.Background(), insertQuery, convoId, members, participants)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while inserting a new conversation: %v", err)
return
}
utils.OkWithJSON(w, fmt.Sprintf(`{
"message": "Conversation created",
"status": 200,
"success": true,
"conversationId": "%v"
}`, convoId))
}
func DeleteMessage(w http.ResponseWriter, req *http.Request) {
body := &models.DeleteMessageBody{}
err := json.NewDecoder(req.Body).Decode(&body)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while decoding request body: %v", err)
return
}
updateQuery := `UPDATE messages SET deleted = true, content = '' WHERE id = $1;`
_, err = db.DBPool.Exec(context.Background(), updateQuery, body.MessageID)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while updating message: %v", err)
return
}
err = os.RemoveAll(fmt.Sprintf("../cdn/messages/%s/%s", body.ConversationID, body.MessageID))
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while deleting message attachment file(s): %v", err)
return
}
deleteQuery := `DELETE FROM message_attachments WHERE message_id = $1;`
_, err = db.DBPool.Exec(context.Background(), deleteQuery, body.MessageID)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while removing message attachment from DB: %v", err)
return
}
utils.OkWithJSON(w, `{
"message": "Deleted message successfully",
"status": 200,
"success": true
}`)
}
func GetConversations(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
pageParam := params["page"]
page, err := strconv.Atoi(pageParam)
if err != nil {
utils.BadRequestWithJSON(w, `{
"message": "Invalid or incomplete request",
"status": 400,
"success": false
}`)
logger.Errorf("Error while converting page param to string: %v", err)
return
}
sessionUser, err := utils.ValidateSession(req, w)
if err != nil {
logger.Error(err)
return
}
query := `SELECT convo.id, convo.last_updated,
receiver.id as receiver_id, receiver.username as receiver_username, receiver.display_name as receiver_display_name, receiver.avatar_url as receiver_avatar_url,
(SELECT content
FROM messages
WHERE conversation_id = convo.id
GROUP BY content
ORDER BY MAX(sent_time) DESC
LIMIT 1) as last_message,
(SELECT author_id
FROM messages
WHERE conversation_id = convo.id
GROUP BY author_id
ORDER BY MAX(sent_time) DESC
LIMIT 1) as last_message_author,
(SELECT attachment.url
FROM messages
LEFT JOIN message_attachments attachment
ON attachment.message_id = messages.id
WHERE conversation_id = convo.id
GROUP BY attachment.url
ORDER BY MAX(sent_time) DESC
LIMIT 1) as last_message_attachment_url,
COUNT(messages) as unread_messages
FROM conversations convo
INNER JOIN users receiver
ON receiver.id <> $1 AND receiver.id = ANY(convo.members)
LEFT JOIN messages
ON messages.conversation_id = convo.id AND $1 <> ALL(messages.read_by)
WHERE $1 = ANY(convo.participants)
GROUP BY convo.id, receiver.id
ORDER BY convo.last_updated DESC
LIMIT 20 OFFSET $2;`
rows, err := db.DBPool.Query(context.Background(), query, sessionUser.ID, page*20)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while fetching conversations: %s", err)
return
}
conversations := make([]models.Conversation, 0)
defer rows.Close()
for rows.Next() {
conversation := &models.Conversation{}
var conversationId uint64
var receiverId uint64
var lastMessageAuthorID uint64
var lastMessageAttachment sql.NullString
err := rows.Scan(&conversationId, &conversation.LastUpdated,
&receiverId, &conversation.Receiver.Username, &conversation.Receiver.DisplayName, &conversation.Receiver.AvatarURL,
&conversation.LastMessage, &lastMessageAuthorID, &lastMessageAttachment,
&conversation.UnreadMessages)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error scanning fields into conversation struct: %s", err)
return
}
conversation.ID = fmt.Sprintf("%v", conversationId)
conversation.Receiver.ID = fmt.Sprintf("%v", receiverId)
if conversation.LastMessage.String == "" && lastMessageAttachment.String != "" {
if lastMessageAuthorID == receiverId {
conversation.LastMessage.String = fmt.Sprintf("%s sent an attachment", conversation.Receiver.DisplayName)
conversation.LastMessage.Valid = true
} else {
conversation.LastMessage.String = "You sent an attachment"
conversation.LastMessage.Valid = true
}
}
conversations = append(conversations, *conversation)
}
utils.OkWithJSON(w, fmt.Sprintf(`{
"message": "Fetched conversations successfully",
"status": 200,
"success": true,
"conversations": %v
}`, utils.MarshalJSON(conversations)))
}
func GetMessages(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
conversationId := params["conversationId"]
pageParam := params["page"]
page, err := strconv.Atoi(pageParam)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while converting page string to int: %v", err)
return
}
_, err = utils.ValidateSession(req, w)
if err != nil {
logger.Error(err)
return
}
query := `SELECT message.id, message.author_id, message.conversation_id, message.content, message.sent_time, message.read_by, message.deleted,
attachment.url, attachment.type
FROM messages message
LEFT JOIN message_attachments attachment
ON attachment.message_id = message.id
WHERE conversation_id = $1
ORDER BY message.sent_time DESC
LIMIT 50 OFFSET $2;`
rows, err := db.DBPool.Query(context.Background(), query, conversationId, page*50)
if err != nil {
if err == pgx.ErrNoRows {
utils.NotFoundWithJSON(w, `{
"message": "No messages were found",
"status": 404,
"success": true
}`)
return
}
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while querying for messages: %v", err)
return
}
messages := make([]models.Message, 0)
for rows.Next() {
message := &models.Message{}
var messageId uint64
var messageAuthorId uint64
var messageConversationId uint64
var readBy pgtype.Int8Array
var attachmentUrl sql.NullString
var attachmentType sql.NullString
err = rows.Scan(&messageId, &messageAuthorId, &messageConversationId, &message.Content, &message.SentTime, &readBy, &message.Deleted,
&attachmentUrl, &attachmentType)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while scanning message data into struct: %v", err)
return
}
if attachmentUrl.Valid && attachmentType.Valid {
message.Attachment.Url = attachmentUrl.String
message.Attachment.Type = attachmentType.String
}
message.ID = fmt.Sprintf("%v", messageId)
message.AuthorID = fmt.Sprintf("%v", messageAuthorId)
message.ConversationID = fmt.Sprintf("%v", messageConversationId)
for _, element := range readBy.Elements {
message.ReadBy = append(message.ReadBy, fmt.Sprintf("%v", element.Int))
}
messages = append(messages, *message)
}
// sort the latest messages by sent time in ascending order
sort.Slice(messages, func(i, j int) bool { return messages[i].SentTime.Before(messages[j].SentTime) })
utils.OkWithJSON(w, fmt.Sprintf(`{
"message": "Successfully fetched messages",
"status": 200,
"success": true,
"messages": %v
}`, utils.MarshalJSON(messages)))
}
func GetUnreadMessages(w http.ResponseWriter, req *http.Request) {
sessionUser, err := utils.ValidateSession(req, w)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Error(err)
return
}
query := `SELECT convo.id FROM conversations convo
INNER JOIN messages
ON messages.conversation_id = convo.id
WHERE $1 <> ALL(messages.read_by)
AND $1 = ANY(convo.participants)
GROUP BY convo.id;`
unread_convos := make([]string, 0)
rows, err := db.DBPool.Query(context.Background(), query, sessionUser.ID)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while querying for unread messages: %v", err)
return
}
defer rows.Close()
for rows.Next() {
var conversationId uint64
err = rows.Scan(&conversationId)
if err != nil {
utils.InternalServerErrorWithJSON(w, "")
logger.Errorf("Error while scanning unread conversations: %v", err)
return
}
unread_convos = append(unread_convos, fmt.Sprintf("%v", conversationId))
}
utils.OkWithJSON(w, fmt.Sprintf(`{
"message": "Fetched unread messages succesfully",
"status": 200,
"success": true,
"unreadMessages": %v
}`, utils.MarshalJSON(unread_convos)))
}