2017-05-08 19:13:29 +02:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"golang.org/x/net/websocket"
|
|
|
|
|
|
|
|
httpLib "github.com/FreifunkBremen/freifunkmanager/lib/http"
|
|
|
|
"github.com/FreifunkBremen/freifunkmanager/lib/log"
|
|
|
|
"github.com/FreifunkBremen/freifunkmanager/runtime"
|
|
|
|
)
|
|
|
|
|
|
|
|
var nodes *runtime.Nodes
|
|
|
|
var clients map[string]*Client
|
|
|
|
|
|
|
|
func Start(nodeBind *runtime.Nodes) {
|
|
|
|
nodes = nodeBind
|
|
|
|
clients = make(map[string]*Client)
|
|
|
|
|
|
|
|
http.Handle("/websocket", websocket.Handler(func(ws *websocket.Conn) {
|
2017-05-09 01:03:44 +02:00
|
|
|
r := ws.Request()
|
|
|
|
ip := httpLib.GetRemoteIP(r)
|
|
|
|
|
2017-05-08 19:13:29 +02:00
|
|
|
defer func() {
|
|
|
|
ws.Close()
|
2017-05-09 01:03:44 +02:00
|
|
|
delete(clients, ip)
|
|
|
|
log.HTTP(r).Info("client disconnected")
|
2017-05-08 19:13:29 +02:00
|
|
|
}()
|
2017-05-09 01:03:44 +02:00
|
|
|
|
2017-05-08 19:13:29 +02:00
|
|
|
log.HTTP(r).Infof("new client")
|
2017-05-09 01:03:44 +02:00
|
|
|
|
2017-05-08 19:13:29 +02:00
|
|
|
client := NewClient(ip, ws)
|
|
|
|
clients[ip] = client
|
|
|
|
client.Listen()
|
2017-05-09 01:03:44 +02:00
|
|
|
|
2017-05-08 19:13:29 +02:00
|
|
|
}))
|
|
|
|
|
|
|
|
nodes.AddNotify(Notify)
|
|
|
|
}
|
|
|
|
|
|
|
|
func Notify(node *runtime.Node, real bool) {
|
2017-05-09 01:03:44 +02:00
|
|
|
msgType := MessageTypeUpdateNode
|
2017-05-08 19:13:29 +02:00
|
|
|
if real {
|
2017-05-09 01:03:44 +02:00
|
|
|
msgType = MessageTypeCurrentNode
|
2017-05-08 19:13:29 +02:00
|
|
|
}
|
|
|
|
for _, c := range clients {
|
2017-05-09 01:03:44 +02:00
|
|
|
c.Write(&Message{Type: msgType, Node: node})
|
2017-05-08 19:13:29 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func Close() {
|
2017-05-09 01:03:44 +02:00
|
|
|
log.Log.Infof("websocket stopped with %d clients", len(clients))
|
2017-05-08 19:13:29 +02:00
|
|
|
}
|