-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatServer.go
291 lines (235 loc) · 6.69 KB
/
chatServer.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
package main
import (
"encoding/json"
"log"
"github.com/1024casts/minichat/config"
"github.com/1024casts/minichat/models"
"github.com/google/uuid"
)
type WsServer struct {
// clients 连接wsServer的客户端
clients map[*Client]bool
register chan *Client
unregister chan *Client
// broadcast 需要广播到客户端的数据
broadcast chan []byte
rooms map[*Room]bool
users []models.User
roomRepository models.RoomRepository
userRepository models.UserRepository
}
// NewWebsocketServer creates a new WsServer type
func NewWebsocketServer(roomRepository models.RoomRepository, userRepository models.UserRepository) *WsServer {
wsServer := &WsServer{
clients: make(map[*Client]bool),
register: make(chan *Client),
unregister: make(chan *Client),
broadcast: make(chan []byte),
rooms: make(map[*Room]bool),
roomRepository: roomRepository,
userRepository: userRepository,
}
// Add users from database to server
wsServer.users = userRepository.GetAllUsers()
return wsServer
}
// Run our websocket server, accepting various requests
func (server *WsServer) Run() {
go server.listenPubSubChannel()
for {
select {
case client := <-server.register:
server.registerClient(client)
case client := <-server.unregister:
server.unregisterClient(client)
case message := <-server.broadcast:
server.broadcastToClients(message)
}
}
}
func (server *WsServer) registerClient(client *Client) {
// NEW: Add user to the repo
server.userRepository.AddUser(client)
//server.notifyClientJoined(client)
// Publish user in PubSub
server.publishClientJoined(client)
server.listOnlineClients(client)
server.clients[client] = true
// NEW: Add user to the user slice
//server.users = append(server.users, message.Sender)
}
func (server *WsServer) unregisterClient(client *Client) {
if _, ok := server.clients[client]; ok {
delete(server.clients, client)
//server.notifyClientLeft(client)
// NEW: Remove user from slice
//for i, user := range server.users {
// if user.GetId() == message.Sender.GetId() {
// server.users[i] = server.users[len(server.users)-1]
// server.users = server.users[:len(server.users)-1]
// }
//}
// NEW: Remove user from repo
server.userRepository.RemoveUser(client)
// Publish user left in PubSub
server.publishClientLeft(client)
}
}
func (server *WsServer) broadcastToClients(message []byte) {
for client := range server.clients {
client.send <- message
}
}
func (server *WsServer) findRoomByName(name string) *Room {
var foundRoom *Room
for room := range server.rooms {
if room.GetName() == name {
foundRoom = room
break
}
}
// NEW: if there is no room, try to create it from the repo
if foundRoom == nil {
// Try to run the room from the repository, if it is found.
foundRoom = server.runRoomFromRepository(name)
}
return foundRoom
}
// NEW: Try to find a room in the repo, if found Run it.
func (server *WsServer) runRoomFromRepository(name string) *Room {
var room *Room
dbRoom := server.roomRepository.FindRoomByName(name)
if dbRoom != nil {
room = NewRoom(dbRoom.GetName(), dbRoom.GetPrivate())
room.ID, _ = uuid.Parse(dbRoom.GetId())
go room.RunRoom()
server.rooms[room] = true
}
return room
}
func (server *WsServer) createRoom(name string, private bool) *Room {
room := NewRoom(name, private)
go room.RunRoom()
server.rooms[room] = true
// NEW: Add room to repo
server.roomRepository.AddRoom(room)
return room
}
func (server *WsServer) notifyClientJoined(client *Client) {
message := &Message{
Action: UserJoinedAction,
Sender: client,
}
server.broadcastToClients(message.encode())
}
func (server *WsServer) notifyClientLeft(client *Client) {
message := &Message{
Action: UserLeftAction,
Sender: client,
}
server.broadcastToClients(message.encode())
}
func (server *WsServer) listOnlineClients(client *Client) {
// NEW: Use the users slice instead of the client map
for _, user := range server.users {
message := &Message{
Action: UserJoinedAction,
Sender: user,
}
client.send <- message.encode()
}
}
func (server *WsServer) findRoomByID(ID string) *Room {
var foundRoom *Room
for room := range server.rooms {
if room.GetId() == ID {
foundRoom = room
break
}
}
return foundRoom
}
func (server *WsServer) findClientByID(ID string) *Client {
var foundClient *Client
for client := range server.clients {
if client.ID.String() == ID {
foundClient = client
break
}
}
return foundClient
}
const PubSubGeneralChannel = "general"
// Publish userJoined message in pub/sub
func (server *WsServer) publishClientJoined(client *Client) {
message := &Message{
Action: UserJoinedAction,
Sender: client,
}
if err := config.Redis.Publish(ctx, PubSubGeneralChannel, message.encode()).Err(); err != nil {
log.Println(err)
}
}
// Publish userleft message in pub/sub
func (server *WsServer) publishClientLeft(client *Client) {
message := &Message{
Action: UserLeftAction,
Sender: client,
}
if err := config.Redis.Publish(ctx, PubSubGeneralChannel, message.encode()).Err(); err != nil {
log.Println(err)
}
}
// Listen to pub/sub general channels
func (server *WsServer) listenPubSubChannel() {
pubsub := config.Redis.Subscribe(ctx, PubSubGeneralChannel)
ch := pubsub.Channel()
for msg := range ch {
var message Message
if err := json.Unmarshal([]byte(msg.Payload), &message); err != nil {
log.Printf("Error on unmarshal JSON message %s", err)
return
}
switch message.Action {
case UserJoinedAction:
server.handleUserJoined(message)
case UserLeftAction:
server.handleUserLeft(message)
case JoinRoomPrivateAction:
server.handleUserJoinPrivate(message)
}
}
}
func (server *WsServer) handleUserJoined(message Message) {
// Add the user to the slice
server.users = append(server.users, message.Sender)
server.broadcastToClients(message.encode())
}
func (server *WsServer) handleUserLeft(message Message) {
// Remove the user from the slice
for i, user := range server.users {
if user.GetId() == message.Sender.GetId() {
server.users[i] = server.users[len(server.users)-1]
server.users = server.users[:len(server.users)-1]
}
}
server.broadcastToClients(message.encode())
}
func (server *WsServer) handleUserJoinPrivate(message Message) {
// Find client for given user, if found add the user to the room.
targetClient := server.findClientByID(message.Message)
if targetClient != nil {
targetClient.joinRoom(message.Target.GetName(), message.Sender)
}
}
// Add the findUserByID method used by client.go
func (server *WsServer) findUserByID(ID string) models.User {
var foundUser models.User
for _, client := range server.users {
if client.GetId() == ID {
foundUser = client
break
}
}
return foundUser
}