mirror of
https://gitlab.com/comunic/ComunicRTCProxy
synced 2024-11-17 11:01:12 +00:00
119 lines
2.1 KiB
Go
119 lines
2.1 KiB
Go
// Websocket controller
|
|
//
|
|
// @author Pierre HUBERT
|
|
|
|
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"os/signal"
|
|
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
// WsMessage is a message from or to the api server
|
|
type WsMessage struct {
|
|
Title string `json:"title"`
|
|
CallHash string `json:"callHash"`
|
|
PeerID string `json:"peerId"`
|
|
Data interface{} `json:"data"`
|
|
}
|
|
|
|
var outMsgChan = make(chan interface{})
|
|
|
|
// Open websocket connection
|
|
func openWs(conf *Config) {
|
|
|
|
// Auto-close connection when the system request it
|
|
interrupt := make(chan os.Signal, 1)
|
|
signal.Notify(interrupt, os.Interrupt)
|
|
|
|
u := conf.getURL()
|
|
log.Printf("Connecting to %s", u.String())
|
|
|
|
// Connect to Websocket
|
|
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
|
|
if err != nil {
|
|
log.Println("dial:", err)
|
|
return
|
|
}
|
|
defer c.Close()
|
|
|
|
// Wait for interrupt signal
|
|
go func() {
|
|
<-interrupt
|
|
c.Close()
|
|
}()
|
|
|
|
// Send outgoing messages
|
|
go func() {
|
|
for {
|
|
c.WriteJSON(<-outMsgChan)
|
|
}
|
|
}()
|
|
|
|
// Read remote messages
|
|
for {
|
|
|
|
_, message, err := c.ReadMessage()
|
|
|
|
if err != nil {
|
|
log.Printf("WS Read error: %s", err.Error())
|
|
return
|
|
}
|
|
|
|
// Process incoming messages
|
|
|
|
// 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{}))
|
|
fmt.Println("Enable video calls:", callConf.allowVideo)
|
|
break
|
|
|
|
// Remote signal
|
|
case "signal":
|
|
onSignal(msg.CallHash, msg.PeerID, msg.Data.(map[string]interface{}))
|
|
break
|
|
|
|
// Request an offer
|
|
case "request_offer":
|
|
onRequestOffer(msg.CallHash, msg.PeerID)
|
|
break
|
|
|
|
// Close a connection
|
|
case "close_conn":
|
|
onCloseConnection(msg.CallHash, msg.PeerID)
|
|
break
|
|
|
|
default:
|
|
println("Received unkown message type!")
|
|
log.Printf("recv: %s", message)
|
|
break
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
/// 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
|
|
}
|