forked from metal3d/kurento-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.go
228 lines (193 loc) · 4.89 KB
/
websocket.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
package kurento
import (
"encoding/json"
"fmt"
"log"
"golang.org/x/net/websocket"
)
// Error that can be filled in response
type Error struct {
Code int64
Message string
Data string
}
const ConnectionLost = -1
// Implements error built-in interface
func (e *Error) Error() string {
return fmt.Sprintf("[%d] %s %s", e.Code, e.Message, e.Data)
}
// Response represents server response
type Response struct {
Jsonrpc string
Id float64
Result map[string]string // should change if result has no several form
Error *Error
}
type Event struct {
Jsonrpc string
Method string
Params map[string]interface{}
Error *Error
}
type Connection struct {
clientId float64
eventId float64
clients map[float64]chan Response
host string
ws *websocket.Conn
SessionId string
events map[string]map[string]map[string]eventHandler // eventName -> objectId -> handlerId -> handler.
Dead chan bool
IsDead bool
}
var connections = make(map[string]*Connection)
func NewConnection(host string) *Connection {
if connections[host] != nil {
return connections[host]
}
c := new(Connection)
connections[host] = c
c.events = make(map[string]map[string]map[string]eventHandler)
c.clients = make(map[float64]chan Response)
c.Dead = make(chan bool, 1)
var err error
c.ws, err = websocket.Dial(host+"/kurento", "", "http://127.0.0.1")
if err != nil {
log.Fatal(err)
}
c.host = host
go c.handleResponse()
return c
}
func (c *Connection) Create(m IMediaObject, options map[string]interface{}) error {
elem := &MediaObject{}
elem.setConnection(c)
return elem.Create(m, options)
}
func (c *Connection) handleResponse() {
for { // run forever
r := Response{}
ev := Event{}
var message string
err := websocket.Message.Receive(c.ws, &message)
if err != nil {
log.Printf("Error receiving on websocket %s", err)
c.IsDead = true
c.Dead <- true
break
}
if debug {
log.Printf("RAW %s", message)
}
// Decode into both possible types. One should be valid
json.Unmarshal([]byte(message), &r)
json.Unmarshal([]byte(message), &ev)
isResponse := r.Id > 0 && r.Result != nil
isEvent := ev.Method == "onEvent"
if isResponse {
if r.Result["sessionId"] != "" {
if debug {
log.Println("sessionId returned ", r.Result["sessionId"])
}
c.SessionId = r.Result["sessionId"]
}
if debug {
log.Printf("Response: %v", r)
}
// if webscocket client exists, send response to the chanel
if c.clients[r.Id] != nil {
c.clients[r.Id] <- r
// chanel is read, we can delete it
delete(c.clients, r.Id)
} else if debug {
log.Println("Dropped message because there is no client ", r.Id)
log.Println(r)
}
} else if isEvent {
val := ev.Params["value"].(map[string]interface{})
if debug {
log.Printf("Received event value %v", val)
}
t := val["type"].(string)
objectId := val["object"].(string)
data := val["data"].(map[string]interface{})
if handlers, ok := c.events[t]; ok {
if objHandlers, ok := handlers[objectId]; ok {
for _, handler := range objHandlers {
handler(data)
}
}
}
} else if debug {
log.Println("Unsupported message from KMS: ", message)
}
}
}
func (c *Connection) Request(req map[string]interface{}) <-chan Response {
if c.IsDead {
errchan := make(chan Response, 1)
errresp := Response{
Id: req["id"].(float64),
Error: &Error{
Code: ConnectionLost,
Message: "No connection to Kurento server",
},
}
errchan <- errresp
return errchan
}
c.clientId++
req["id"] = c.clientId
if c.SessionId != "" {
req["sessionId"] = c.SessionId
}
c.clients[c.clientId] = make(chan Response)
if debug {
j, _ := json.MarshalIndent(req, "", " ")
log.Println("json", string(j))
}
err := websocket.JSON.Send(c.ws, req)
if err != nil {
log.Printf("Error sending on websocket %s", err)
c.Dead <- true
c.IsDead = true
delete(c.clients, c.clientId)
errchan := make(chan Response, 1)
errresp := Response{
Id: req["id"].(float64),
Error: &Error{
Code: ConnectionLost,
Message: "No connection to Kurento server",
},
}
errchan <- errresp
return errchan
}
return c.clients[c.clientId]
}
func (c *Connection) Subscribe(event, objectId, handlerId string, handler eventHandler) {
var oh map[string]map[string]eventHandler
var ok bool
if oh, ok = c.events[event]; !ok {
c.events[event] = make(map[string]map[string]eventHandler)
oh = c.events[event]
}
var he map[string]eventHandler
if he, ok = oh[objectId]; !ok {
oh[objectId] = make(map[string]eventHandler)
he = oh[objectId]
}
he[handlerId] = handler
}
func (c *Connection) Unsubscribe(event, objectId, handlerId string) {
var oh map[string]map[string]eventHandler
var he map[string]eventHandler
var ok bool
if oh, ok = c.events[event]; !ok {
return // not found
}
if he, ok = oh[objectId]; !ok {
return // not found
}
delete(he, handlerId)
}