freifunkmanager/websocket/server.go

71 lines
1.9 KiB
Go
Raw Normal View History

2017-05-08 19:13:29 +02:00
package websocket
import (
2018-08-10 17:17:00 +02:00
"time"
2017-05-08 19:13:29 +02:00
2018-07-26 14:14:23 +02:00
wsLib "dev.sum7.eu/genofire/golang-lib/websocket"
"github.com/jinzhu/gorm"
log "github.com/sirupsen/logrus"
2017-05-08 19:13:29 +02:00
2018-07-26 14:14:23 +02:00
"github.com/FreifunkBremen/yanic/runtime"
2017-05-08 19:13:29 +02:00
)
type WebsocketServer struct {
2018-08-10 17:17:00 +02:00
nodes *runtime.Nodes
db *gorm.DB
blacklistFor time.Duration
secret string
ipPrefix string
ws *wsLib.WebsocketHandlerService
}
2017-05-08 19:13:29 +02:00
func websocketHandlerFunc(f func(logger *log.Entry, msg *wsLib.Message) error) wsLib.MessageHandleFunc {
return func(msg *wsLib.Message) {
logger := log.WithFields(log.Fields{
"session": msg.Session,
"id": msg.ID,
"subject": msg.Subject,
})
err := f(logger, msg)
if err != nil {
logger.Warnf("websocket message '%s' cound not handle: %s", msg.Subject, err)
}
}
}
2018-08-10 17:17:00 +02:00
func NewWebsocketServer(secret string, ipPrefix string, db *gorm.DB, blacklistFor time.Duration, nodes *runtime.Nodes) *WebsocketServer {
ownWS := WebsocketServer{
2018-08-10 17:17:00 +02:00
nodes: nodes,
db: db,
blacklistFor: blacklistFor,
secret: secret,
ipPrefix: ipPrefix,
}
ownWS.ws = wsLib.NewWebsocketHandlerService()
// Register Handlers
ownWS.ws.SetHandler(MessageTypeConnect, websocketHandlerFunc(ownWS.connectHandler))
ownWS.ws.SetHandler(MessageTypeLogin, websocketHandlerFunc(ownWS.loginHandler))
ownWS.ws.SetHandler(MessageTypeAuthStatus, websocketHandlerFunc(ownWS.authStatusHandler))
ownWS.ws.SetHandler(MessageTypeSettings, websocketHandlerFunc(ownWS.settingsHandler))
ownWS.ws.SetHandler(MessageTypeLogout, websocketHandlerFunc(ownWS.logoutHandler))
2017-05-08 19:13:29 +02:00
ownWS.ws.SetHandler(MessageTypeNode, websocketHandlerFunc(ownWS.nodeHandler))
ownWS.ws.FallbackHandler = func(msg *wsLib.Message) {
log.WithFields(log.Fields{
"session": msg.Session,
"id": msg.ID,
"subject": msg.Subject,
}).Warnf("websocket message '%s' cound not handle", msg.Subject)
}
2017-05-08 19:13:29 +02:00
ownWS.ws.Listen("/ws")
return &ownWS
2017-05-08 19:13:29 +02:00
}
func (ws *WebsocketServer) Close() {
ws.ws.Close()
2017-05-08 19:13:29 +02:00
}