This repository was archived by the owner on Oct 10, 2023. It is now read-only.
forked from AFathi/live-webrtcsignaling
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathroom.go
80 lines (68 loc) · 1.79 KB
/
room.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
package main
import (
"context"
"sync/atomic"
"time"
plogger "github.com/heytribe/go-plogger"
"github.com/heytribe/live-webrtcsignaling/my"
)
var gRoomId uint64
type Room struct {
my.NamedRWMutex
dateCreation time.Time
id uint64
connections []*connection
}
func NewRoom() *Room {
room := new(Room)
room.id = atomic.AddUint64(&gRoomId, 1)
room.dateCreation = time.Now()
room.connections = []*connection{}
room.NamedRWMutex.Init("room:%d", room.id)
return room
}
// not thread safe
func (room *Room) GetConnection(socketId string) *connection {
for i := 0; i < len(room.connections); i++ {
c := room.connections[i]
if c.socketId == socketId {
return c
}
}
return nil
}
// not thread safe
func (room *Room) Remove(ctx context.Context, socketId string) *connection {
log := plogger.FromContextSafe(ctx)
for i := 0; i < len(room.connections); i++ {
c := room.connections[i]
if c.socketId == socketId {
room.connections = append(room.connections[:i], room.connections[i+1:]...)
log.Infof("room: removing websocket %s, new room size", socketId, len(room.connections))
return c
}
}
return nil
}
func (room *Room) Range(ctx context.Context, f func(int, *connection)) {
room.RLock(ctx)
defer room.RUnlock(ctx)
for i, conn := range room.connections {
f(i, conn)
}
}
// JSON marshaling
type jsonRoom struct {
Id RoomId `json:"id"`
DateCreation time.Time `json:"dateCreation"`
Connections []*connection `json:"connections"`
}
// note: had to insert room connections directly into jsonRooms instead of embedding a room in jsonRoom (and declaring
// MarshalJSON() in the room struct) because of https://stackoverflow.com/q/38489776
func newJsonRoom(id RoomId, room *Room) jsonRoom {
return jsonRoom{
id,
room.dateCreation,
room.connections,
}
}