-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws_handlers.go
160 lines (131 loc) · 3.69 KB
/
ws_handlers.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
package main
import (
"encoding/json"
"time"
"github.com/gofiber/contrib/websocket"
"github.com/gofiber/fiber/v2/log"
"gorm.io/gorm"
)
// userID to websocket connection
var websocketConnections = map[uint]*websocket.Conn{}
type BaseMessageSchema struct {
Type string
}
type JoinChatRequestSchema struct {
BaseMessageSchema
ChatID uint
UserID uint
}
type SendMessageRequestSchema struct {
BaseMessageSchema
ChatID uint
UserID uint
Message string
}
type BroadcastMessageSchema struct {
BaseMessageSchema
FromUserEmail string
Message string
}
func WebsocketHandler(c *websocket.Conn) {
db, ok := c.Locals("db").(*gorm.DB)
if !ok {
log.Fatal("error getting `db` from c.Locals()")
}
for {
messageType, message, err := c.ReadMessage()
if err != nil {
log.Infof("read error:", err)
break
}
log.Infof("recv: %d %+v", messageType, string(message))
var v BaseMessageSchema
err = json.Unmarshal(message, &v)
if err != nil {
log.Fatal("json unmarshall WebsocketRequestSchema error: %s\n", err)
}
switch messageType := v.Type; messageType {
case "join_chat":
handleJoinChat(c, message)
case "send_message":
// get users that are in chat and not userID
handleSendMessage(db, message)
default:
log.Errorf("unhandled message type=%s v=%s\n", messageType, v)
}
}
}
func handleSendMessage(db *gorm.DB, message []byte) {
var requestData SendMessageRequestSchema
err := json.Unmarshal(message, &requestData)
if err != nil {
log.Fatalf("json unmarshall SendMessageRequestSchema error: %s\n", err)
}
log.Infof("`send message` message=%+v\n", requestData)
messageContent := string(requestData.Message)
log.Infof("messageContent=%s\n", messageContent)
messageObj := Message{
ChatID: requestData.ChatID,
FromID: requestData.UserID,
Content: messageContent,
}
tx := db.Create(&messageObj)
if tx.Error != nil {
log.Fatal(tx.Error)
}
userIDsToSendMessageTo, err := getChatUsersExcept(db, requestData.ChatID, requestData.UserID)
if err != nil {
log.Fatalf("getChatUsersExcept err=%s\n", err)
}
log.Infof("will send message to userIDsToSendMessageTo=%+v\n", userIDsToSendMessageTo)
for _, userID := range userIDsToSendMessageTo {
sendMessageToUser(db, userID, messageContent)
}
}
func sendMessageToUser(db *gorm.DB, userID uint, messageContent string) {
memberConn := websocketConnections[userID]
if memberConn == nil {
log.Infof("no connection for userID=%d\n", userID)
return
}
twentySecondFromNow := time.Now().Add(time.Second * 10)
err := memberConn.WriteControl(websocket.PingMessage, []byte("hello from the other side"), twentySecondFromNow)
if err != nil {
log.Fatal(err)
}
var fromUser User
err = db.Find(&fromUser, userID).Error
if err != nil {
log.Fatalf("get user by id failed id=%d\n", userID)
}
broadcastMessageData := BroadcastMessageSchema{
BaseMessageSchema: BaseMessageSchema{
Type: "new_message",
},
FromUserEmail: fromUser.Email,
Message: messageContent,
}
b, err := json.Marshal(broadcastMessageData)
if err != nil {
log.Fatalf("json marshall err:%s\n", err)
}
err = memberConn.WriteMessage(websocket.TextMessage, b)
if err != nil {
log.Fatalf("error WriteMessage %s\n", err)
}
}
func handleJoinChat(c *websocket.Conn, message []byte) {
var requestData JoinChatRequestSchema
err := json.Unmarshal(message, &requestData)
if err != nil {
log.Fatalf("json unmarshall JoinChatRequestSchema error: %s\n", err)
}
log.Infof("`join chat` message=%+v\n", requestData)
userID := requestData.UserID
_, exists := websocketConnections[userID]
if exists {
websocketConnections[userID].Close()
}
websocketConnections[userID] = c
// TODO: broadcast to other users in chat, than a new user has joined
}