matterbridge/gateway/samechannel/samechannel.go

78 lines
2.0 KiB
Go
Raw Normal View History

2016-09-30 14:19:47 -07:00
package samechannelgateway
import (
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config"
log "github.com/Sirupsen/logrus"
"strings"
)
type SameChannelGateway struct {
*config.Config
MyConfig *config.SameChannelGateway
2016-11-13 14:06:37 -08:00
Bridges map[string]*bridge.Bridge
2016-09-30 14:19:47 -07:00
Channels []string
ignoreNicks map[string][]string
Name string
}
func New(cfg *config.Config, gateway *config.SameChannelGateway) error {
c := make(chan config.Message)
gw := &SameChannelGateway{}
2016-11-13 14:06:37 -08:00
gw.Bridges = make(map[string]*bridge.Bridge)
2016-09-30 14:19:47 -07:00
gw.Name = gateway.Name
gw.Config = cfg
gw.MyConfig = gateway
gw.Channels = gateway.Channels
for _, account := range gateway.Accounts {
br := config.Bridge{Account: account}
log.Infof("Starting bridge: %s", account)
2016-11-13 14:06:37 -08:00
gw.Bridges[account] = bridge.New(cfg, &br, c)
2016-09-30 14:19:47 -07:00
}
for _, br := range gw.Bridges {
err := br.Connect()
if err != nil {
2016-11-13 14:06:37 -08:00
log.Fatalf("Bridge %s failed to start: %v", br.Account, err)
}
2016-09-30 14:19:47 -07:00
for _, channel := range gw.Channels {
2016-11-13 14:06:37 -08:00
log.Infof("%s: joining %s", br.Account, channel)
2016-09-30 14:19:47 -07:00
br.JoinChannel(channel)
}
}
gw.handleReceive(c)
return nil
}
func (gw *SameChannelGateway) handleReceive(c chan config.Message) {
for {
select {
case msg := <-c:
for _, br := range gw.Bridges {
gw.handleMessage(msg, br)
}
}
}
}
2016-11-13 14:06:37 -08:00
func (gw *SameChannelGateway) handleMessage(msg config.Message, dest *bridge.Bridge) {
2016-09-30 14:19:47 -07:00
// do not send the message to the bridge we come from if also the channel is the same
2016-11-13 14:06:37 -08:00
if msg.Account == dest.Account {
2016-09-30 14:19:47 -07:00
return
}
2016-11-13 14:06:37 -08:00
gw.modifyUsername(&msg, dest)
log.Debugf("Sending %#v from %s to %s", msg, msg.Account, dest.Account)
err := dest.Send(msg)
if err != nil {
log.Error(err)
}
2016-09-30 14:19:47 -07:00
}
2016-11-13 14:06:37 -08:00
func (gw *SameChannelGateway) modifyUsername(msg *config.Message, dest *bridge.Bridge) {
br := gw.Bridges[msg.Account]
nick := dest.Config.RemoteNickFormat
nick = strings.Replace(nick, "{NICK}", msg.Username, -1)
nick = strings.Replace(nick, "{BRIDGE}", br.Name, -1)
nick = strings.Replace(nick, "{PROTOCOL}", br.Protocol, -1)
msg.Username = nick
2016-09-30 14:19:47 -07:00
}