4
0
mirror of https://github.com/cwinfo/matterbridge.git synced 2025-06-26 00:39:24 +00:00

Make all loggers derive from non-default instance (#728)

This commit is contained in:
Wim
2019-02-23 22:51:27 +01:00
committed by GitHub
parent 1bb39eba87
commit bf21604d42
28 changed files with 2934 additions and 270 deletions

View File

@ -10,7 +10,7 @@ import (
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config"
"github.com/d5/tengo/script"
"github.com/hashicorp/golang-lru"
lru "github.com/hashicorp/golang-lru"
"github.com/peterhellberg/emojilib"
"github.com/sirupsen/logrus"
)
@ -26,6 +26,8 @@ type Gateway struct {
Message chan config.Message
Name string
Messages *lru.Cache
logger *logrus.Entry
}
type BrMsgID struct {
@ -34,25 +36,30 @@ type BrMsgID struct {
ChannelID string
}
var flog *logrus.Entry
const apiProtocol = "api"
const (
apiProtocol = "api"
)
// New creates a new Gateway object associated with the specified router and
// following the given configuration.
func New(rootLogger *logrus.Logger, cfg *config.Gateway, r *Router) *Gateway {
logger := rootLogger.WithFields(logrus.Fields{"prefix": "gateway"})
func New(cfg config.Gateway, r *Router) *Gateway {
flog = logrus.WithFields(logrus.Fields{"prefix": "gateway"})
gw := &Gateway{Channels: make(map[string]*config.ChannelInfo), Message: r.Message,
Router: r, Bridges: make(map[string]*bridge.Bridge), Config: r.Config}
cache, _ := lru.New(5000)
gw.Messages = cache
if err := gw.AddConfig(&cfg); err != nil {
flog.Errorf("AddConfig failed: %s", err)
gw := &Gateway{
Channels: make(map[string]*config.ChannelInfo),
Message: r.Message,
Router: r,
Bridges: make(map[string]*bridge.Bridge),
Config: r.Config,
Messages: cache,
logger: logger,
}
if err := gw.AddConfig(cfg); err != nil {
logger.Errorf("Failed to add configuration to gateway: %#v", err)
}
return gw
}
// Find the canonical ID that the message is keyed under in cache
// FindCanonicalMsgID returns the ID under which a message was stored in the cache.
func (gw *Gateway) FindCanonicalMsgID(protocol string, mID string) string {
ID := protocol + " " + mID
if gw.Messages.Contains(ID) {
@ -72,15 +79,18 @@ func (gw *Gateway) FindCanonicalMsgID(protocol string, mID string) string {
return ""
}
// AddBridge sets up a new bridge in the gateway object with the specified configuration.
func (gw *Gateway) AddBridge(cfg *config.Bridge) error {
br := gw.Router.getBridge(cfg.Account)
if br == nil {
br = bridge.New(cfg)
br.Config = gw.Router.Config
br.General = &gw.BridgeValues().General
// set logging
br.Log = logrus.WithFields(logrus.Fields{"prefix": "bridge"})
brconfig := &bridge.Config{Remote: gw.Message, Log: logrus.WithFields(logrus.Fields{"prefix": br.Protocol}), Bridge: br}
br.Log = gw.logger.WithFields(logrus.Fields{"prefix": br.Protocol})
brconfig := &bridge.Config{
Remote: gw.Message,
Bridge: br,
}
// add the actual bridger for this protocol to this bridge using the bridgeMap
br.Bridger = gw.Router.BridgeMap[br.Protocol](brconfig)
}
@ -89,11 +99,12 @@ func (gw *Gateway) AddBridge(cfg *config.Bridge) error {
return nil
}
// AddConfig associates a new configuration with the gateway object.
func (gw *Gateway) AddConfig(cfg *config.Gateway) error {
gw.Name = cfg.Name
gw.MyConfig = cfg
if err := gw.mapChannels(); err != nil {
flog.Errorf("mapChannels() failed: %s", err)
gw.logger.Errorf("mapChannels() failed: %s", err)
}
for _, br := range append(gw.MyConfig.In, append(gw.MyConfig.InOut, gw.MyConfig.Out...)...) {
br := br //scopelint
@ -115,20 +126,20 @@ func (gw *Gateway) mapChannelsToBridge(br *bridge.Bridge) {
func (gw *Gateway) reconnectBridge(br *bridge.Bridge) {
if err := br.Disconnect(); err != nil {
flog.Errorf("Disconnect() %s failed: %s", br.Account, err)
gw.logger.Errorf("Disconnect() %s failed: %s", br.Account, err)
}
time.Sleep(time.Second * 5)
RECONNECT:
flog.Infof("Reconnecting %s", br.Account)
gw.logger.Infof("Reconnecting %s", br.Account)
err := br.Connect()
if err != nil {
flog.Errorf("Reconnection failed: %s. Trying again in 60 seconds", err)
gw.logger.Errorf("Reconnection failed: %s. Trying again in 60 seconds", err)
time.Sleep(time.Second * 60)
goto RECONNECT
}
br.Joined = make(map[string]bool)
if err := br.JoinChannels(); err != nil {
flog.Errorf("JoinChannels() %s failed: %s", br.Account, err)
gw.logger.Errorf("JoinChannels() %s failed: %s", br.Account, err)
}
}
@ -142,13 +153,19 @@ func (gw *Gateway) mapChannelConfig(cfg []config.Bridge, direction string) {
br.Channel = strings.ToLower(br.Channel)
}
if strings.HasPrefix(br.Account, "mattermost.") && strings.HasPrefix(br.Channel, "#") {
flog.Errorf("Mattermost channels do not start with a #: remove the # in %s", br.Channel)
gw.logger.Errorf("Mattermost channels do not start with a #: remove the # in %s", br.Channel)
os.Exit(1)
}
ID := br.Channel + br.Account
if _, ok := gw.Channels[ID]; !ok {
channel := &config.ChannelInfo{Name: br.Channel, Direction: direction, ID: ID, Options: br.Options, Account: br.Account,
SameChannel: make(map[string]bool)}
channel := &config.ChannelInfo{
Name: br.Channel,
Direction: direction,
ID: ID,
Options: br.Options,
Account: br.Account,
SameChannel: make(map[string]bool),
}
channel.SameChannel[gw.Name] = br.SameChannel
gw.Channels[channel.ID] = channel
} else {
@ -207,7 +224,7 @@ func (gw *Gateway) getDestChannel(msg *config.Message, dest bridge.Bridge) []con
// if source channel is in only, do nothing
for _, channel := range gw.Channels {
// lookup the channel from the message
if channel.ID == getChannelID(*msg) {
if channel.ID == getChannelID(msg) {
// we only have destinations if the original message is from an "in" (sending) channel
if !strings.Contains(channel.Direction, "in") {
return channels
@ -216,11 +233,11 @@ func (gw *Gateway) getDestChannel(msg *config.Message, dest bridge.Bridge) []con
}
}
for _, channel := range gw.Channels {
if _, ok := gw.Channels[getChannelID(*msg)]; !ok {
if _, ok := gw.Channels[getChannelID(msg)]; !ok {
continue
}
// do samechannelgateway flogic
// do samechannelgateway logic
if channel.SameChannel[msg.Gateway] {
if msg.Channel == channel.Name && msg.Account != dest.Account {
channels = append(channels, *channel)
@ -234,7 +251,7 @@ func (gw *Gateway) getDestChannel(msg *config.Message, dest bridge.Bridge) []con
return channels
}
func (gw *Gateway) getDestMsgID(msgID string, dest *bridge.Bridge, channel config.ChannelInfo) string {
func (gw *Gateway) getDestMsgID(msgID string, dest *bridge.Bridge, channel *config.ChannelInfo) string {
if res, ok := gw.Messages.Get(msgID); ok {
IDs := res.([]*BrMsgID)
for _, id := range IDs {
@ -263,7 +280,7 @@ func (gw *Gateway) ignoreTextEmpty(msg *config.Message) bool {
len(msg.Extra[config.EventFileFailureSize]) > 0) {
return false
}
flog.Debugf("ignoring empty message %#v from %s", msg, msg.Account)
gw.logger.Debugf("ignoring empty message %#v from %s", msg, msg.Account)
return true
}
@ -282,7 +299,7 @@ func (gw *Gateway) ignoreMessage(msg *config.Message) bool {
return false
}
func (gw *Gateway) modifyUsername(msg config.Message, dest *bridge.Bridge) string {
func (gw *Gateway) modifyUsername(msg *config.Message, dest *bridge.Bridge) string {
br := gw.Bridges[msg.Account]
msg.Protocol = br.Protocol
if dest.GetBool("StripNick") {
@ -298,7 +315,7 @@ func (gw *Gateway) modifyUsername(msg config.Message, dest *bridge.Bridge) strin
// TODO move compile to bridge init somewhere
re, err := regexp.Compile(search)
if err != nil {
flog.Errorf("regexp in %s failed: %s", msg.Account, err)
gw.logger.Errorf("regexp in %s failed: %s", msg.Account, err)
break
}
msg.Username = re.ReplaceAllString(msg.Username, replace)
@ -326,7 +343,7 @@ func (gw *Gateway) modifyUsername(msg config.Message, dest *bridge.Bridge) strin
return nick
}
func (gw *Gateway) modifyAvatar(msg config.Message, dest *bridge.Bridge) string {
func (gw *Gateway) modifyAvatar(msg *config.Message, dest *bridge.Bridge) string {
iconurl := dest.GetString("IconURL")
iconurl = strings.Replace(iconurl, "{NICK}", msg.Username, -1)
if msg.Avatar == "" {
@ -337,7 +354,7 @@ func (gw *Gateway) modifyAvatar(msg config.Message, dest *bridge.Bridge) string
func (gw *Gateway) modifyMessage(msg *config.Message) {
if err := modifyMessageTengo(gw.BridgeValues().General.TengoModifyMessage, msg); err != nil {
flog.Errorf("TengoModifyMessage failed: %s", err)
gw.logger.Errorf("TengoModifyMessage failed: %s", err)
}
// replace :emoji: to unicode
@ -351,7 +368,7 @@ func (gw *Gateway) modifyMessage(msg *config.Message) {
// TODO move compile to bridge init somewhere
re, err := regexp.Compile(search)
if err != nil {
flog.Errorf("regexp in %s failed: %s", msg.Account, err)
gw.logger.Errorf("regexp in %s failed: %s", msg.Account, err)
break
}
msg.Text = re.ReplaceAllString(msg.Text, replace)
@ -365,46 +382,51 @@ func (gw *Gateway) modifyMessage(msg *config.Message) {
}
}
// SendMessage sends a message (with specified parentID) to the channel on the selected destination bridge.
// returns a message id and error.
func (gw *Gateway) SendMessage(origmsg config.Message, dest *bridge.Bridge, channel config.ChannelInfo, canonicalParentMsgID string) (string, error) {
msg := origmsg
// SendMessage sends a message (with specified parentID) to the channel on the selected
// destination bridge and returns a message ID or an error.
func (gw *Gateway) SendMessage(
rmsg *config.Message,
dest *bridge.Bridge,
channel *config.ChannelInfo,
canonicalParentMsgID string,
) (string, error) {
msg := *rmsg
// Only send the avatar download event to ourselves.
if msg.Event == config.EventAvatarDownload {
if channel.ID != getChannelID(origmsg) {
if channel.ID != getChannelID(rmsg) {
return "", nil
}
} else {
// do not send to ourself for any other event
if channel.ID == getChannelID(origmsg) {
if channel.ID == getChannelID(rmsg) {
return "", nil
}
}
// Too noisy to log like other events
if msg.Event != config.EventUserTyping {
flog.Debugf("=> Sending %#v from %s (%s) to %s (%s)", msg, msg.Account, origmsg.Channel, dest.Account, channel.Name)
gw.logger.Debugf("=> Sending %#v from %s (%s) to %s (%s)", msg, msg.Account, rmsg.Channel, dest.Account, channel.Name)
}
msg.Channel = channel.Name
msg.Avatar = gw.modifyAvatar(origmsg, dest)
msg.Username = gw.modifyUsername(origmsg, dest)
msg.Avatar = gw.modifyAvatar(rmsg, dest)
msg.Username = gw.modifyUsername(rmsg, dest)
msg.ID = gw.getDestMsgID(origmsg.Protocol+" "+origmsg.ID, dest, channel)
msg.ID = gw.getDestMsgID(rmsg.Protocol+" "+rmsg.ID, dest, channel)
// for api we need originchannel as channel
if dest.Protocol == apiProtocol {
msg.Channel = origmsg.Channel
msg.Channel = rmsg.Channel
}
msg.ParentID = gw.getDestMsgID(origmsg.Protocol+" "+canonicalParentMsgID, dest, channel)
msg.ParentID = gw.getDestMsgID(rmsg.Protocol+" "+canonicalParentMsgID, dest, channel)
if msg.ParentID == "" {
msg.ParentID = canonicalParentMsgID
}
// if the parentID is still empty and we have a parentID set in the original message
// this means that we didn't find it in the cache so set it "msg-parent-not-found"
if msg.ParentID == "" && origmsg.ParentID != "" {
if msg.ParentID == "" && rmsg.ParentID != "" {
msg.ParentID = "msg-parent-not-found"
}
@ -421,7 +443,7 @@ func (gw *Gateway) SendMessage(origmsg config.Message, dest *bridge.Bridge, chan
// append the message ID (mID) from this bridge (dest) to our brMsgIDs slice
if mID != "" {
flog.Debugf("mID %s: %s", dest.Account, mID)
gw.logger.Debugf("mID %s: %s", dest.Account, mID)
return mID, nil
//brMsgIDs = append(brMsgIDs, &BrMsgID{dest, dest.Protocol + " " + mID, channel.ID})
}
@ -432,7 +454,7 @@ func (gw *Gateway) validGatewayDest(msg *config.Message) bool {
return msg.Gateway == gw.Name
}
func getChannelID(msg config.Message) string {
func getChannelID(msg *config.Message) string {
return msg.Channel + msg.Account
}
@ -449,11 +471,11 @@ func (gw *Gateway) ignoreText(text string, input []string) bool {
// TODO do not compile regexps everytime
re, err := regexp.Compile(entry)
if err != nil {
flog.Errorf("incorrect regexp %s", entry)
gw.logger.Errorf("incorrect regexp %s", entry)
continue
}
if re.MatchString(text) {
flog.Debugf("matching %s. ignoring %s", entry, text)
gw.logger.Debugf("matching %s. ignoring %s", entry, text)
return true
}
}

View File

@ -2,12 +2,15 @@ package gateway
import (
"fmt"
"io/ioutil"
"strconv"
"testing"
"github.com/42wim/matterbridge/bridge/config"
"github.com/42wim/matterbridge/gateway/bridgemap"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
var testconfig = []byte(`
@ -159,8 +162,10 @@ const (
)
func maketestRouter(input []byte) *Router {
cfg := config.NewConfigFromString(input)
r, err := NewRouter(cfg, bridgemap.FullMap)
logger := logrus.New()
logger.SetOutput(ioutil.Discard)
cfg := config.NewConfigFromString(logger, input)
r, err := NewRouter(logger, cfg, bridgemap.FullMap)
if err != nil {
fmt.Println(err)
}
@ -387,7 +392,23 @@ func TestGetDestChannelAdvanced(t *testing.T) {
assert.Equal(t, map[string]int{"bridge3": 4, "bridge": 9, "announcements": 3, "bridge2": 4}, hits)
}
func TestIgnoreTextEmpty(t *testing.T) {
type ignoreTestSuite struct {
suite.Suite
gw *Gateway
}
func TestIgnoreSuite(t *testing.T) {
s := &ignoreTestSuite{}
suite.Run(t, s)
}
func (s *ignoreTestSuite) SetupSuite() {
logger := logrus.New()
logger.SetOutput(ioutil.Discard)
s.gw = &Gateway{logger: logrus.NewEntry(logger)}
}
func (s *ignoreTestSuite) TestIgnoreTextEmpty() {
extraFile := make(map[string][]interface{})
extraAttach := make(map[string][]interface{})
extraFailure := make(map[string][]interface{})
@ -424,15 +445,14 @@ func TestIgnoreTextEmpty(t *testing.T) {
output: true,
},
}
gw := &Gateway{}
for testname, testcase := range msgTests {
output := gw.ignoreTextEmpty(testcase.input)
assert.Equalf(t, testcase.output, output, "case '%s' failed", testname)
output := s.gw.ignoreTextEmpty(testcase.input)
s.Assert().Equalf(testcase.output, output, "case '%s' failed", testname)
}
}
func TestIgnoreTexts(t *testing.T) {
func (s *ignoreTestSuite) TestIgnoreTexts() {
msgTests := map[string]struct {
input string
re []string
@ -459,14 +479,13 @@ func TestIgnoreTexts(t *testing.T) {
output: true,
},
}
gw := &Gateway{}
for testname, testcase := range msgTests {
output := gw.ignoreText(testcase.input, testcase.re)
assert.Equalf(t, testcase.output, output, "case '%s' failed", testname)
output := s.gw.ignoreText(testcase.input, testcase.re)
s.Assert().Equalf(testcase.output, output, "case '%s' failed", testname)
}
}
func TestIgnoreNicks(t *testing.T) {
func (s *ignoreTestSuite) TestIgnoreNicks() {
msgTests := map[string]struct {
input string
re []string
@ -493,10 +512,9 @@ func TestIgnoreNicks(t *testing.T) {
output: false,
},
}
gw := &Gateway{}
for testname, testcase := range msgTests {
output := gw.ignoreText(testcase.input, testcase.re)
assert.Equalf(t, testcase.output, output, "case '%s' failed", testname)
output := s.gw.ignoreText(testcase.input, testcase.re)
s.Assert().Equalf(testcase.output, output, "case '%s' failed", testname)
}
}

View File

@ -40,7 +40,7 @@ func (r *Router) handleEventGetChannelMembers(msg *config.Message) {
for _, br := range gw.Bridges {
if msg.Account == br.Account {
cMembers := msg.Extra[config.EventGetChannelMembers][0].(config.ChannelMembers)
flog.Debugf("Syncing channelmembers from %s", msg.Account)
r.logger.Debugf("Syncing channelmembers from %s", msg.Account)
br.SetChannelMembers(&cMembers)
return
}
@ -58,7 +58,7 @@ func (r *Router) handleEventRejoinChannels(msg *config.Message) {
if msg.Account == br.Account {
br.Joined = make(map[string]bool)
if err := br.JoinChannels(); err != nil {
flog.Errorf("channel join failed for %s: %s", msg.Account, err)
r.logger.Errorf("channel join failed for %s: %s", msg.Account, err)
}
}
}
@ -94,13 +94,13 @@ func (gw *Gateway) handleFiles(msg *config.Message) {
if gw.BridgeValues().General.MediaServerUpload != "" {
// Use MediaServerUpload. Upload using a PUT HTTP request and basicauth.
if err := gw.handleFilesUpload(&fi); err != nil {
flog.Error(err)
gw.logger.Error(err)
continue
}
} else {
// Use MediaServerPath. Place the file on the current filesystem.
if err := gw.handleFilesLocal(&fi); err != nil {
flog.Error(err)
gw.logger.Error(err)
continue
}
}
@ -108,7 +108,7 @@ func (gw *Gateway) handleFiles(msg *config.Message) {
// Download URL.
durl := gw.BridgeValues().General.MediaServerDownload + "/" + sha1sum + "/" + fi.Name
flog.Debugf("mediaserver download URL = %s", durl)
gw.logger.Debugf("mediaserver download URL = %s", durl)
// We uploaded/placed the file successfully. Add the SHA and URL.
extra := msg.Extra["file"][i].(config.FileInfo)
@ -133,7 +133,7 @@ func (gw *Gateway) handleFilesUpload(fi *config.FileInfo) error {
return fmt.Errorf("mediaserver upload failed, could not create request: %#v", err)
}
flog.Debugf("mediaserver upload url: %s", url)
gw.logger.Debugf("mediaserver upload url: %s", url)
req.Header.Set("Content-Type", "binary/octet-stream")
_, err = client.Do(req)
@ -154,7 +154,7 @@ func (gw *Gateway) handleFilesLocal(fi *config.FileInfo) error {
}
path := dir + "/" + fi.Name
flog.Debugf("mediaserver path placing file: %s", path)
gw.logger.Debugf("mediaserver path placing file: %s", path)
err = ioutil.WriteFile(path, *fi.Data, os.ModePerm)
if err != nil {
@ -187,36 +187,36 @@ func (gw *Gateway) ignoreEvent(event string, dest *bridge.Bridge) bool {
// handleMessage makes sure the message get sent to the correct bridge/channels.
// Returns an array of msg ID's
func (gw *Gateway) handleMessage(msg config.Message, dest *bridge.Bridge) []*BrMsgID {
func (gw *Gateway) handleMessage(rmsg *config.Message, dest *bridge.Bridge) []*BrMsgID {
var brMsgIDs []*BrMsgID
// if we have an attached file, or other info
if msg.Extra != nil && len(msg.Extra[config.EventFileFailureSize]) != 0 && msg.Text == "" {
if rmsg.Extra != nil && len(rmsg.Extra[config.EventFileFailureSize]) != 0 && rmsg.Text == "" {
return brMsgIDs
}
if gw.ignoreEvent(msg.Event, dest) {
if gw.ignoreEvent(rmsg.Event, dest) {
return brMsgIDs
}
// broadcast to every out channel (irc QUIT)
if msg.Channel == "" && msg.Event != config.EventJoinLeave {
flog.Debug("empty channel")
if rmsg.Channel == "" && rmsg.Event != config.EventJoinLeave {
gw.logger.Debug("empty channel")
return brMsgIDs
}
// Get the ID of the parent message in thread
var canonicalParentMsgID string
if msg.ParentID != "" && dest.GetBool("PreserveThreading") {
canonicalParentMsgID = gw.FindCanonicalMsgID(msg.Protocol, msg.ParentID)
if rmsg.ParentID != "" && dest.GetBool("PreserveThreading") {
canonicalParentMsgID = gw.FindCanonicalMsgID(rmsg.Protocol, rmsg.ParentID)
}
origmsg := msg
channels := gw.getDestChannel(&msg, *dest)
for _, channel := range channels {
msgID, err := gw.SendMessage(origmsg, dest, channel, canonicalParentMsgID)
channels := gw.getDestChannel(rmsg, *dest)
for idx := range channels {
channel := &channels[idx]
msgID, err := gw.SendMessage(rmsg, dest, channel, canonicalParentMsgID)
if err != nil {
flog.Errorf("SendMessage failed: %s", err)
gw.logger.Errorf("SendMessage failed: %s", err)
continue
}
if msgID == "" {
@ -235,7 +235,7 @@ func (gw *Gateway) handleExtractNicks(msg *config.Message) {
replace := outer[1]
msg.Username, msg.Text, err = extractNick(search, replace, msg.Username, msg.Text)
if err != nil {
flog.Errorf("regexp in %s failed: %s", msg.Account, err)
gw.logger.Errorf("regexp in %s failed: %s", msg.Account, err)
break
}
}

View File

@ -7,31 +7,40 @@ import (
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config"
samechannelgateway "github.com/42wim/matterbridge/gateway/samechannel"
"github.com/42wim/matterbridge/gateway/samechannel"
"github.com/sirupsen/logrus"
)
type Router struct {
config.Config
sync.RWMutex
BridgeMap map[string]bridge.Factory
Gateways map[string]*Gateway
Message chan config.Message
MattermostPlugin chan config.Message
sync.RWMutex
logger *logrus.Entry
}
func NewRouter(cfg config.Config, bridgeMap map[string]bridge.Factory) (*Router, error) {
// NewRouter initializes a new Matterbridge router for the specified configuration and
// sets up all required gateways.
func NewRouter(rootLogger *logrus.Logger, cfg config.Config, bridgeMap map[string]bridge.Factory) (*Router, error) {
logger := rootLogger.WithFields(logrus.Fields{"prefix": "router"})
r := &Router{
Config: cfg,
BridgeMap: bridgeMap,
Message: make(chan config.Message),
MattermostPlugin: make(chan config.Message),
Gateways: make(map[string]*Gateway),
logger: logger,
}
sgw := samechannelgateway.New(cfg)
gwconfigs := sgw.GetConfig()
sgw := samechannel.New(cfg)
gwconfigs := append(sgw.GetConfig(), cfg.BridgeValues().Gateway...)
for _, entry := range append(gwconfigs, cfg.BridgeValues().Gateway...) {
for idx := range gwconfigs {
entry := &gwconfigs[idx]
if !entry.Enable {
continue
}
@ -41,21 +50,23 @@ func NewRouter(cfg config.Config, bridgeMap map[string]bridge.Factory) (*Router,
if _, ok := r.Gateways[entry.Name]; ok {
return nil, fmt.Errorf("Gateway with name %s already exists", entry.Name)
}
r.Gateways[entry.Name] = New(entry, r)
r.Gateways[entry.Name] = New(rootLogger, entry, r)
}
return r, nil
}
// Start will connect all gateways belonging to this router and subsequently route messages
// between them.
func (r *Router) Start() error {
m := make(map[string]*bridge.Bridge)
for _, gw := range r.Gateways {
flog.Infof("Parsing gateway %s", gw.Name)
r.logger.Infof("Parsing gateway %s", gw.Name)
for _, br := range gw.Bridges {
m[br.Account] = br
}
}
for _, br := range m {
flog.Infof("Starting bridge: %s ", br.Account)
r.logger.Infof("Starting bridge: %s ", br.Account)
err := br.Connect()
if err != nil {
e := fmt.Errorf("Bridge %s failed to start: %v", br.Account, err)
@ -77,7 +88,7 @@ func (r *Router) Start() error {
for _, gw := range r.Gateways {
for i, br := range gw.Bridges {
if br.Bridger == nil {
flog.Errorf("removing failed bridge %s", i)
r.logger.Errorf("removing failed bridge %s", i)
delete(gw.Bridges, i)
}
}
@ -91,7 +102,7 @@ func (r *Router) Start() error {
// otherwise returns false
func (r *Router) disableBridge(br *bridge.Bridge, err error) bool {
if r.BridgeValues().General.IgnoreFailureOnStart {
flog.Error(err)
r.logger.Error(err)
// setting this bridge empty
*br = bridge.Bridge{}
return true
@ -124,7 +135,7 @@ func (r *Router) handleReceive() {
gw.modifyMessage(&msg)
gw.handleFiles(&msg)
for _, br := range gw.Bridges {
msgIDs = append(msgIDs, gw.handleMessage(msg, br)...)
msgIDs = append(msgIDs, gw.handleMessage(&msg, br)...)
}
// only add the message ID if it doesn't already exists
if _, ok := gw.Messages.Get(msg.Protocol + " " + msg.ID); !ok && msg.ID != "" {
@ -146,9 +157,9 @@ func (r *Router) updateChannelMembers() {
if br.Protocol != "slack" {
continue
}
flog.Debugf("sending %s to %s", config.EventGetChannelMembers, br.Account)
r.logger.Debugf("sending %s to %s", config.EventGetChannelMembers, br.Account)
if _, err := br.Send(config.Message{Event: config.EventGetChannelMembers}); err != nil {
flog.Errorf("updateChannelMembers: %s", err)
r.logger.Errorf("updateChannelMembers: %s", err)
}
}
}

View File

@ -1,4 +1,4 @@
package samechannelgateway
package samechannel
import (
"github.com/42wim/matterbridge/bridge/config"

View File

@ -1,9 +1,11 @@
package samechannelgateway
package samechannel
import (
"io/ioutil"
"testing"
"github.com/42wim/matterbridge/bridge/config"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
)
@ -66,7 +68,9 @@ var (
)
func TestGetConfig(t *testing.T) {
cfg := config.NewConfigFromString([]byte(testConfig))
logger := logrus.New()
logger.SetOutput(ioutil.Discard)
cfg := config.NewConfigFromString(logger, []byte(testConfig))
sgw := New(cfg)
configs := sgw.GetConfig()
assert.Equal(t, []config.Gateway{expectedConfig}, configs)