logmania/output/websocket/main.go

105 lines
2.1 KiB
Go
Raw Normal View History

2018-04-26 21:05:27 +02:00
package xmpp
import (
"net/http"
2018-09-11 20:20:58 +02:00
"regexp"
2018-04-26 21:05:27 +02:00
"dev.sum7.eu/genofire/golang-lib/websocket"
2018-09-05 01:53:23 +02:00
"github.com/mitchellh/mapstructure"
2018-04-26 21:05:27 +02:00
log "github.com/sirupsen/logrus"
"dev.sum7.eu/genofire/logmania/bot"
"dev.sum7.eu/genofire/logmania/database"
2018-09-05 01:53:23 +02:00
"dev.sum7.eu/genofire/logmania/output"
2018-04-26 21:05:27 +02:00
)
const (
proto = "ws"
)
2018-09-05 01:53:23 +02:00
var logger = log.WithField("output", proto)
2018-04-26 21:05:27 +02:00
2018-09-05 01:53:23 +02:00
type Output struct {
output.Output
defaults []*database.Notify
2018-04-26 21:05:27 +02:00
ws *websocket.Server
formatter log.Formatter
}
2018-09-05 01:53:23 +02:00
type OutputConfig struct {
Default string `mapstructure:"default"`
}
func Init(configInterface interface{}, db *database.DB, bot *bot.Bot) output.Output {
var config OutputConfig
if err := mapstructure.Decode(configInterface, &config); err != nil {
logger.Warnf("not able to decode data: %s", err)
return nil
}
2018-04-26 21:05:27 +02:00
inputMSG := make(chan *websocket.Message)
ws := websocket.NewServer(inputMSG, nil)
2018-09-05 01:53:23 +02:00
http.HandleFunc("/output/ws", ws.Handler)
2018-04-26 21:05:27 +02:00
go func() {
for msg := range inputMSG {
if msg.Subject != "bot" {
logger.Warnf("receive unknown websocket message: %s", msg.Subject)
continue
}
bot.Handle(func(answer string) {
msg.Answer("bot", answer)
}, "", msg.Body.(string))
}
}()
2018-09-05 01:53:23 +02:00
logger.Info("startup")
var defaults []*database.Notify
2018-09-05 01:53:23 +02:00
if config.Default != "" {
defaults = append(defaults, &database.Notify{
2018-09-11 20:20:58 +02:00
Protocol: proto,
To: config.Default,
RegexIn: make(map[string]*regexp.Regexp),
MaxPrioIn: log.DebugLevel,
})
}
2018-09-05 01:53:23 +02:00
return &Output{
defaults: defaults,
ws: ws,
2018-04-26 21:05:27 +02:00
formatter: &log.TextFormatter{
DisableTimestamp: true,
},
}
}
2018-09-05 01:53:23 +02:00
func (out *Output) Default() []*database.Notify {
return out.defaults
}
2018-09-05 01:53:23 +02:00
func (out *Output) Send(e *log.Entry, to *database.Notify) bool {
2018-04-26 21:05:27 +02:00
if to.Protocol != proto {
return false
}
2018-05-18 14:04:54 +02:00
2018-09-05 01:53:23 +02:00
out.ws.SendAll(&websocket.Message{
2018-04-26 21:05:27 +02:00
Subject: to.Address(),
2018-05-18 14:04:54 +02:00
Body: &log.Entry{
Buffer: e.Buffer,
Data: e.Data,
Level: e.Level,
Logger: e.Logger,
Message: to.RunReplace(e.Message),
Time: e.Time,
},
2018-04-26 21:05:27 +02:00
})
return true
}
2018-09-05 01:53:23 +02:00
func (out *Output) Close() {
2018-04-26 21:05:27 +02:00
}
func init() {
2018-09-05 01:53:23 +02:00
output.Add("websocket", Init)
2018-04-26 21:05:27 +02:00
}