ComunicRTCProxy/ws.go

119 lines
2.1 KiB
Go
Raw Normal View History

2020-04-10 07:43:14 +00:00
// Websocket controller
//
// @author Pierre HUBERT
package main
import (
2020-04-10 08:38:21 +00:00
"encoding/json"
2020-04-12 15:36:27 +00:00
"fmt"
2020-04-10 07:43:14 +00:00
"log"
2020-04-10 08:14:16 +00:00
"os"
"os/signal"
2020-04-10 07:43:14 +00:00
"github.com/gorilla/websocket"
)
2020-04-10 08:38:21 +00:00
// WsMessage is a message from or to the api server
type WsMessage struct {
2020-04-11 11:16:06 +00:00
Title string `json:"title"`
CallHash string `json:"callHash"`
PeerID string `json:"peerId"`
Data interface{} `json:"data"`
2020-04-10 08:38:21 +00:00
}
2020-04-11 10:14:55 +00:00
var outMsgChan = make(chan interface{})
2020-04-10 07:43:14 +00:00
// Open websocket connection
func openWs(conf *Config) {
2020-04-10 08:14:16 +00:00
// Auto-close connection when the system request it
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
2020-04-10 07:43:14 +00:00
u := conf.getURL()
log.Printf("Connecting to %s", u.String())
// Connect to Websocket
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
2020-04-12 15:24:49 +00:00
log.Println("dial:", err)
return
2020-04-10 07:43:14 +00:00
}
defer c.Close()
2020-04-10 08:14:16 +00:00
// Wait for interrupt signal
go func() {
<-interrupt
c.Close()
}()
2020-04-11 10:14:55 +00:00
// Send outgoing messages
go func() {
for {
c.WriteJSON(<-outMsgChan)
}
}()
2020-04-10 07:43:14 +00:00
// Read remote messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Printf("WS Read error: %s", err.Error())
return
}
2020-04-10 08:38:21 +00:00
// Process incoming messages
2020-04-10 07:43:14 +00:00
2020-04-10 08:38:21 +00:00
// Decode JSON
var msg WsMessage
json.Unmarshal(message, &msg)
switch msg.Title {
// call configuration
case "config":
println("Got call configuration")
setCallConfig(msg.Data.(map[string]interface{}))
2020-04-12 15:36:27 +00:00
fmt.Println("Enable video calls:", callConf.allowVideo)
2020-04-10 08:38:21 +00:00
break
2020-04-11 08:30:28 +00:00
// Remote signal
case "signal":
onSignal(msg.CallHash, msg.PeerID, msg.Data.(map[string]interface{}))
break
2020-04-11 16:20:46 +00:00
// Request an offer
case "request_offer":
onRequestOffer(msg.CallHash, msg.PeerID)
break
2020-04-11 16:02:50 +00:00
// Close a connection
case "close_conn":
onCloseConnection(msg.CallHash, msg.PeerID)
break
2020-04-11 08:30:28 +00:00
default:
println("Received unkown message type!")
2020-04-11 14:32:34 +00:00
log.Printf("recv: %s", message)
2020-04-11 08:30:28 +00:00
break
2020-04-10 08:38:21 +00:00
}
2020-04-10 07:43:14 +00:00
}
}
2020-04-11 10:14:55 +00:00
/// Send a signal to the API
func sendSignal(callHash, peerID string, data interface{}) {
msg := WsMessage{
Title: "signal",
PeerID: peerID,
CallHash: callHash,
Data: data,
}
outMsgChan <- msg
}