generated from isso0424/golang-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
316 lines (246 loc) · 6.4 KB
/
server.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
package main
import (
"context"
"fmt"
"io"
"log"
"math/rand"
"sync"
pb "github.com/ProvinDevs/2020vol5-backend/types"
)
type Room struct {
id int32
joinedUserIds map[string]pb.Hello_SignallingServer
}
const (
roomIdMin = 10000
roomIdMax = 99999
roomMaxCount = roomIdMax - roomIdMin
)
type Server struct {
pb.UnimplementedHelloServer
mu sync.Mutex
rooms []*Room
}
func (s *Server) newRoom() *Room {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.rooms) >= roomMaxCount {
log.Fatalln("roomMaxCount exceeded")
}
retry:
id := int32((rand.Int() % (roomIdMax - roomIdMin + 1)) + roomIdMin)
for _, v := range s.rooms {
if v.id == id {
goto retry
}
}
newRoom := Room{id: id, joinedUserIds: make(map[string]pb.Hello_SignallingServer)}
s.rooms = append(s.rooms, &newRoom)
log.Printf("New Room(%d) has created\n", newRoom.id)
printCurrentRooms(&s.rooms)
return &newRoom
}
func (s *Server) CreateRoom(_ context.Context, _ *pb.CreateRoomRequest) (*pb.Room, error) {
newRoom := s.newRoom()
pbRoom := pb.Room{
RoomId: int32(newRoom.id),
JoinedUserIds: []string{},
}
return &pbRoom, nil
}
func (s *Server) Signalling(stream pb.Hello_SignallingServer) error {
worker := Worker{
mu: &s.mu,
rooms: &s.rooms,
room: nil,
st: stream,
userId: "",
}
return worker.start()
}
type Worker struct {
mu *sync.Mutex
rooms *[]*Room
room *Room
st pb.Hello_SignallingServer
userId string
}
func (w *Worker) start() error {
return w.recvRoutine()
}
func (w *Worker) recvRoutine() error {
for {
msg, err := w.st.Recv()
if err == io.EOF {
w.onStreamClose()
return nil
}
if err != nil {
w.onStreamClose()
return err
}
w.onMessage(msg)
}
}
func (w *Worker) onStreamClose() {
log.Printf("User %s has left\n", w.userId)
w.mu.Lock()
defer w.mu.Unlock()
emptyRoomIndexes := []int{}
for index, room := range *w.rooms {
delete(room.joinedUserIds, w.userId)
if len(room.joinedUserIds) == 0 {
emptyRoomIndexes = append(emptyRoomIndexes, index)
}
}
// remove empty rooms from w.rooms
for _, index := range emptyRoomIndexes {
log.Printf("Room %d has dropped.\n", (*w.rooms)[index].id)
(*w.rooms)[index] = (*w.rooms)[len(*w.rooms)-1]
(*w.rooms)[len(*w.rooms)-1] = &Room{}
*w.rooms = (*w.rooms)[:len(*w.rooms)-1]
}
printCurrentRooms(w.rooms)
}
func (w *Worker) onMessage(msg *pb.SendSignallingMessage) {
body := msg.GetBody()
switch typedBody := body.(type) {
case *pb.SendSignallingMessage_SelfIntro:
log.Println("SelfIntroMessage has came")
w.onSelfIntroduce(typedBody.SelfIntro)
case *pb.SendSignallingMessage_RoomInfoRequest:
log.Printf("RoomInfoRequest has came from %s\n", w.userId)
w.onRoomInfoRequest()
case *pb.SendSignallingMessage_SdpMessage:
log.Printf("SdpMessage has came from %s\n", w.userId)
w.onSdpMessage(typedBody.SdpMessage)
case *pb.SendSignallingMessage_IceMessage:
log.Printf("IceMessage has came from %s\n", w.userId)
w.onIceCandidateMessage(typedBody.IceMessage)
default:
log.Printf("%s has sent message which has unknown message in body: %#v\n", w.userId, body)
}
}
func (w *Worker) sendSelfIntroResult(ok bool, msg string) {
w.st.Send(
&pb.RecvSignallingMessage{
Body: &pb.RecvSignallingMessage_SelfIntroResult{
SelfIntroResult: &pb.SelfIntroduceResult{
Ok: ok,
ErrorMessage: msg,
},
},
},
)
}
func (w *Worker) onSelfIntroduce(msg *pb.SelfIntroduceMessage) {
w.mu.Lock()
defer w.mu.Unlock()
if w.userId != "" && w.room != nil {
log.Printf("%s has self-introduced twice\n", w.userId)
w.sendSelfIntroResult(false, "this is your second self-introducing and it's not allowed.")
return
}
userId := msg.GetMyId()
roomId := msg.GetRoomId()
w.userId = userId
ok := false
for _, v := range *w.rooms {
if _, exists := v.joinedUserIds[userId]; exists {
log.Printf("Duplicated UserID %s\n", userId)
w.sendSelfIntroResult(false, "UserID is duplicated. Change to another one.")
}
}
for _, v := range *w.rooms {
if v.id == roomId {
w.room = v
w.room.joinedUserIds[userId] = w.st
ok = true
break
}
}
if !ok {
log.Printf("%s tried to join room %d which doesn't exist.\n", userId, roomId)
w.sendSelfIntroResult(false, "specified room doesn't exist")
return
}
w.sendSelfIntroResult(true, "")
log.Printf("User %s joined to room %d\n", msg.GetMyId(), roomId)
}
func (w *Worker) onRoomInfoRequest() {
w.mu.Lock()
defer w.mu.Unlock()
if w.room == nil {
log.Println("? has requested RoomInfo without self-introducing")
return
}
joinedUserIds := make([]string, 0, len(w.room.joinedUserIds))
for k := range w.room.joinedUserIds {
joinedUserIds = append(joinedUserIds, k)
}
msg := pb.RecvSignallingMessage{
Body: &pb.RecvSignallingMessage_RoomInfoResponse{
RoomInfoResponse: &pb.Room{
RoomId: w.room.id,
JoinedUserIds: joinedUserIds,
},
},
}
w.st.Send(&msg)
}
func (w *Worker) onSdpMessage(msg *pb.SendSdpMessage) {
w.mu.Lock()
defer w.mu.Unlock()
if w.userId == "" {
log.Printf("? has requested to send Sdp to %s without self-introducing\n", msg.GetToId())
return
}
toId := msg.GetToId()
sendMsg := &pb.RecvSignallingMessage{
Body: &pb.RecvSignallingMessage_SdpMessage{
SdpMessage: &pb.RecvSdpMessage{
SessionDescription: msg.GetSessionDescription(),
FromId: w.userId,
ToId: toId,
},
},
}
w.sendToOtherUserInSameRoom(toId, sendMsg)
}
func (w *Worker) onIceCandidateMessage(msg *pb.SendIceCandidateMessage) {
w.mu.Lock()
defer w.mu.Unlock()
if w.userId == "" {
log.Printf("? has requested to send IceCandidate to %s without self-introducing\n", msg.GetToId())
return
}
toId := msg.GetToId()
sendMsg := &pb.RecvSignallingMessage{
Body: &pb.RecvSignallingMessage_IceMessage{
IceMessage: &pb.RecvIceCandidateMessage{
IceCandidate: msg.GetIceCandidate(),
FromId: w.userId,
ToId: toId,
},
},
}
w.sendToOtherUserInSameRoom(toId, sendMsg)
}
// THIS FUNCTION EXPECT THAT w.mu IS ALREADY LOCKED
func (w *Worker) sendToOtherUserInSameRoom(userId string, msg *pb.RecvSignallingMessage) bool {
for streamUserId, stream := range w.room.joinedUserIds {
if streamUserId == userId {
stream.Send(msg)
return true
}
}
return false
}
func printCurrentRooms(rooms *[]*Room) {
buffer := ""
for _, room := range *rooms {
buffer += fmt.Sprintf("%d, ", room.id)
}
log.Printf("current rooms are: %s", buffer)
}